﻿'*******************************************************************
' Program: Data Center Visio Rack Tool
' Author: Albert E Edlund
' Date:
'
' Purpose: This is the drill down to get a list of racks to draw
'   Added a map control so that we didn't have to go elsewhere when
'       we want to track down the latitude and longitude of a location/
'       sublocation
'   Still using a URRI structure to keep the rack location drilldown data
'
' for maps
' http://www.microsoft.com/downloads/details.aspx?FamilyID=8bb43b9c-6e1f-4e5c-84a6-86c326a0d025&displaylang=en
' "United States Maps(US units).vss
'
'*******************************************************************


Imports Microsoft.Practices.EnterpriseLibrary.Common
Imports Microsoft.Practices.EnterpriseLibrary.ExceptionHandling
Imports Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging

Imports Microsoft.Office.Interop
Imports Microsoft.Office.Interop.Excel
Imports AxMicrosoft.Office.Interop.VisOcx
Imports Microsoft.Office.Interop.Visio
Imports System.Runtime.InteropServices
Imports System.Reflection
Imports MapPoint

Imports System
Imports System.IO
Imports System.Object
Imports System.Math
Imports visRackLocations.clsDC_RackData
Imports System.Collections
Imports System.Collections.Generic
Imports System.Collections.ObjectModel
Imports System.Drawing.Color

Imports System.Data
Imports System.Data.OleDb



Public Class frmLocationData


#Region " Drawing Constants "



    ' the internal container stencil
    Const masterContainerStencilU As String = ""
    ' our default container
    Const masterContainerNameU As String = "Container 3"
    ' wireframe stencil for list (vertical w/header on top) control
    Const stencilWFControl As String = "wfctrl_u.vss"
    ' wireframe master for vertical list
    Const masterListBox As String = "List box"
    ' wireframe master for vertical list item
    Const masterListBoxItem As String = "List box item"
    ' wireframe stencil for list (vertical w/header on side and horizontal) toolbar 
    Const stencilWFToolbar As String = "wftlbr_u.vss"
    Const masterMenuBar As String = "Menu bar"
    Const masterMenuBarItem As String = "Menu bar item"
    Const masterDropDown As String = "Drop-down menu"
    Const masterDropDownItem As String = "Menu item"

    Const constDefaultContainerHeight As String = "1 in"
    Const constDefaultContainerWidth As String = "2 in"
    ' start .75 from left side of page and the top
    Const constDefaultContainerMargin As String = "0.75 in"

#End Region

#Region " Properties and definitions "


    ' our utilities for visio
    Private _clsVisio As clsVisioSupport

    ' our data source class
    Private _clsData As visRackLocations.clsDC_RackData

    ' our reporting class
    Private _clsReports As visRackLocations.clsDC_RackReporting

    Dim blnExcelSource As Boolean

    ' flag that we are testing with other than
    ' sql server data
    Private blnExternalSource As Boolean

    '
    ' the mapping control properties
    '
    Private _mappingControl As AxMappointControl
    Public Property mappingControl() As AxMappointControl
        Get
            Return Me._mappingControl
        End Get
        Set(ByVal value As AxMappointControl)
            Me._mappingControl = value
        End Set
    End Property

    Private _mappingApplication As MapPoint.Application
    Public Property mappingApplication() As MapPoint.Application
        Get
            Return Me._mappingApplication
        End Get
        Set(ByVal value As MapPoint.Application)
            If (value Is Nothing) Then
                Throw New System.ArgumentNullException("mappingApplication", _
                    "mappingApplication is Null.")
            End If
            Me._mappingApplication = value
        End Set
    End Property

    Private _mappingMap As MapPoint.Map
    Public Property mappingMap() As MapPoint.Map
        Get
            Return Me._mappingMap
        End Get
        Set(ByVal value As MapPoint.Map)
            If (value Is Nothing) Then
                Throw New System.ArgumentNullException("mappingMap", _
                    "mappingMap is Null.")
            End If
            Me._mappingMap = value
        End Set
    End Property


    Private _mappingLocation As MapPoint.Location
    Public Property mappingLocation() As MapPoint.Location
        Get
            Return Me._mappingLocation
        End Get
        Set(ByVal value As MapPoint.Location)
            If (value Is Nothing) Then
                Throw New System.ArgumentNullException("mappingLocation", _
                    "mappingLocation is Null.")
            End If
            Me._mappingLocation = value
        End Set
    End Property



    '
    ' the drawing control properties
    '
    '********* visio snippet vb.net vis0042vb ******************
    Private _drawingControl As AxMicrosoft.Office.Interop.VisOcx.AxDrawingControl
    Public Property drawingControl() As AxMicrosoft.Office.Interop.VisOcx.AxDrawingControl
        Get
            Return Me._drawingControl
        End Get
        Set(ByVal value As AxMicrosoft.Office.Interop.VisOcx.AxDrawingControl)
            Me._drawingControl = value
        End Set
    End Property


    '********* visio snippet vb.net vis0041vb ******************
    Private _drawingApplication As Microsoft.Office.Interop.Visio.Application
    Private Property drawingApplication() As Microsoft.Office.Interop.Visio.Application
        Get
            Return Me._drawingApplication
        End Get
        Set(ByVal value As Microsoft.Office.Interop.Visio.Application)
            If (value Is Nothing) Then
                Throw New System.ArgumentNullException("visioApplication", _
                    "drawingApplication is Null.")
            End If
            Me._drawingApplication = value
        End Set
    End Property


    '********* visio snippet vb.net vis0043vb ******************
    Private _drawingDocument As Microsoft.Office.Interop.Visio.Document
    Private Property drawingDocument() As Microsoft.Office.Interop.Visio.Document
        Get
            Return Me._drawingDocument
        End Get
        Set(ByVal value As Microsoft.Office.Interop.Visio.Document)
            If (value Is Nothing) Then
                Throw New System.ArgumentNullException("visioDocument", _
                    "drawingDocument is Null.")
            End If
            Me._drawingDocument = value
        End Set
    End Property

    '********* visio snippet vb.net vis0045vb ******************
    Private _drawingWindow As Microsoft.Office.Interop.Visio.Window
    Private Property drawingWindow() As Microsoft.Office.Interop.Visio.Window
        Get
            Return Me._drawingWindow
        End Get
        Set(ByVal value As Microsoft.Office.Interop.Visio.Window)
            If (value Is Nothing) Then
                Throw New System.ArgumentNullException("visioWindow", _
                    "drawingWindow is Null.")
            End If
            Me._drawingWindow = value
        End Set
    End Property
    '********* visio snippet vb.net vis0044vb ******************
    Private _drawingPage As Microsoft.Office.Interop.Visio.Page
    Private Property drawingPage() As Microsoft.Office.Interop.Visio.Page
        Get
            Return Me._drawingPage
        End Get
        Set(ByVal value As Microsoft.Office.Interop.Visio.Page)
            If (value Is Nothing) Then
                Throw New System.ArgumentNullException("visioPage", _
                    "drawingPage is Null.")
            End If
            Me._drawingPage = value
        End Set
    End Property

    '
    ' solution specific
    '

    Const connectedlayerNameU As String = "ConnectedRack"
    Const selectedLayerNameU As String = "SelectedRack"
    '
    '
    '
    Private _currRowKey As Int32
    Public Property currRowKey As Int32
        Get
            Return _currRowKey
        End Get
        Set(ByVal value As Int32)
            _currRowKey = value
        End Set
    End Property
    '
    '
    '
    Private _currSubLocKey As Int32
    Public Property currSubLocKey As Int32
        Get
            Return _currSubLocKey
        End Get
        Set(ByVal value As Int32)
            _currSubLocKey = value
        End Set
    End Property
    '
    '
    '
    Private _currClientKey As Int32
    Public Property currClientKey As Int32
        Get
            Return _currClientKey
        End Get
        Set(ByVal value As Int32)
            _currClientKey = value
        End Set
    End Property
    '
    '
    '
    Private _currLocKey As Int32
    Public Property currLocKey As Int32
        Get
            Return _currLocKey
        End Get
        Set(ByVal value As Int32)
            _currLocKey = value
        End Set
    End Property
    '
    '
    '
    Private _lastURRI As clsDC_RackData.rackURRI
    Public Property LastUrri As clsDC_RackData.rackURRI
        Get
            Return _lastURRI
        End Get
        Set(ByVal value As clsDC_RackData.rackURRI)
            _lastURRI = value
            ' write it to the statusbar
            Dim colKeyURRI As Collection = New Collection
            colKeyURRI.Add(value.clientKey.ToString)
            currClientKey = value.clientKey
            colKeyURRI.Add(value.locKey.ToString)
            currLocKey = value.locKey
            colKeyURRI.Add(value.attrlocKey.ToString)
            currSubLocKey = value.attrlocKey
            colKeyURRI.Add(value.rowKey.ToString)
            currRowKey = value.rowKey
            colKeyURRI.Add(value.rckKey.ToString)
            Dim strKeyURRI As String = BuildCsvString(colKeyURRI)
            sblStatusOne.Text = "LastUrri"
            sblStatusTwo.Text = strKeyURRI
        End Set
    End Property

    '
    ' where is the base stencil (shapes, datagraphic masters)
    '
    Public m_customstencilpath As String = My.Settings.path_custom_stencils
    Public Property _CustomStencilPath() As String
        Get
            Return Me.m_customstencilpath
        End Get
        Set(ByVal value As String)
            Me.m_customstencilpath = value
        End Set
    End Property

    '
    ' where is the test excel workbook
    '
    Public m_customdatapath As String = My.Settings.path_custom_data
    Public Property _CustomDataPath As String
        Get
            Return Me.m_customdatapath
        End Get
        Set(ByVal value As String)
            Me.m_customdatapath = value
        End Set
    End Property

    '
    '
    '
    Private m_dictComponents As Dictionary(Of Integer, String)
    Public Property dictComponents() As Dictionary(Of Integer, String)
        Get
            If m_dictComponents Is Nothing Then
                m_dictComponents = New Dictionary(Of Integer, String)
            End If
            dictComponents = m_dictComponents
        End Get
        Set(ByVal value As Dictionary(Of Integer, String))
            m_dictComponents = value
        End Set
    End Property

    '
    '
    '
    Private m_dictLinks As Dictionary(Of Integer, String)
    Public Property dictLinks() As Dictionary(Of Integer, String)
        Get
            If m_dictLinks Is Nothing Then
                m_dictLinks = New Dictionary(Of Integer, String)
            End If
            dictLinks = m_dictLinks
        End Get
        Set(ByVal value As Dictionary(Of Integer, String))
            m_dictLinks = value
        End Set
    End Property

    '
    '
    '
    Private m_dictConnected As Dictionary(Of Integer, String)
    Public Property dictConnected() As Dictionary(Of Integer, String)
        Get
            If m_dictConnected Is Nothing Then
                m_dictConnected = New Dictionary(Of Integer, String)
            End If
            dictConnected = m_dictLinks
        End Get
        Set(ByVal value As Dictionary(Of Integer, String))
            m_dictConnected = value
        End Set
    End Property


#End Region

#Region " Constructor "


    Public Sub New()

        ' This call is required by the designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.


        Try



            drawingControl = visLocationControl

            InitTheDrawingControl()

            ' this will use the mouse action as a rack selection inside the drawing
            AddHandler drawingWindow.MouseUp, AddressOf mouseUp_EventHandler

            _clsVisio = New clsVisioSupport()
            _clsVisio.drawingApplication = drawingApplication
            _clsVisio.drawingDocument = drawingDocument


            'setup a default grid
            setupPageGrid(drawingPage)

            'these are dictionaries for document pages with shapeid's being the keys, and shape names
            m_dictLinks = New Dictionary(Of Integer, String)
            m_dictComponents = New Dictionary(Of Integer, String)
            m_dictConnected = New Dictionary(Of Integer, String)

            ' create our data cache
            If _clsData Is Nothing Then
                _clsData = New clsDC_RackData
            Else
                _clsData = Nothing
                _clsData = New clsDC_RackData
            End If

            ' keep the data cache in sync with the drawing control
            _clsData.drawingApplication = drawingApplication
            ' make the imported datatables available as datarecordsets within the document for later use by the enduser
            _clsData.drawingDocument = drawingDocument

            currLocKey = -1
            currSubLocKey = -1

            ' whether to use our excel test source or not
            blnExcelSource = True

            If blnExcelSource = False Then

                loadTestLocationData()

            Else

                loadTestDictTables()
                loadExcelTestData()

            End If

            Me.ConnectedRacksToolStripMenuItem.Enabled = Not (blnExcelSource)

            'since the data is loaded display the hierarchy
            drawTreeview()

            'prep the mappoint control
            mappingControl = mapLocationControl


        Catch com As COMException
            ' add com exception handler here
            '********* visio snippet vb.net vis0056vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(com, "Com+ Policy")
            If (rethrow) Then
                Throw
            End If

        Catch ex As Exception
            ' add exception handler here
            '********* visio snippet vb.net vis0059vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If

        End Try

    End Sub


    '********* visio snippet vb.net vis0049vb ******************

    ' Properties and Definitions
    Private Const defaultDocumentName As String = "LocationDocument"
    Private Const defaultPageName As String = "LocationExample"

    Private Sub InitTheDrawingControl()

        Try

            '
            ' get the pointers
            '
            ' make sure the control does not change the pagesizebehavior
            Me.drawingControl.PageSizingBehavior = VisPageSizingBehaviors.visNeverResizePages

            Me.drawingWindow = Me.drawingControl.Window
            Me.drawingWindow.Activate()
            Me.drawingApplication = Me.drawingControl.Window.Application

            Me.drawingDocument = Me.drawingControl.Document
            Dim docSheet As Microsoft.Office.Interop.Visio.Shape = Me.drawingDocument.DocumentSheet
            docSheet.NameU = defaultDocumentName
            Me.drawingDocument.DiagramServicesEnabled = VisDiagramServices.visServiceVersion140

            Me.drawingPage = Me.drawingControl.Window.Page
            Me.drawingPage.NameU = defaultPageName
            drawingWindow.Page = drawingPage

            Me.drawingApplication.Application.Settings.EnableAutoConnect = False
            Me.drawingApplication.OnDataChangeDelay = -2

            Me.drawingWindow.ShowGrid = False
            Me.drawingWindow.ShowPageTabs = True
            Me.drawingWindow.ShowRulers = False
            Me.drawingWindow.ShowScrollBars = True


        Catch com As COMException
            ' add com exception handler here
            '********* visio snippet vb.net vis0056vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(com, "Com+ Policy")
            If (rethrow) Then
                Throw
            End If

        Catch ex As Exception
            ' add exception handler here
            '********* visio snippet vb.net vis0059vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If

        End Try

    End Sub


    Protected Overrides Sub Finalize()


        If Not (drawingDocument Is Nothing) Then
            drawingDocument.Saved = True
            _drawingDocument = Nothing
            CType(_drawingApplication, Microsoft.Office.Interop.Visio.Application).Quit()
            _drawingApplication = Nothing
        End If

        If Not (mappingMap Is Nothing) Then
            mappingMap.Saved = True  ' Forestall the "Save Changes?" dialog
            _mappingMap = Nothing
            CType(_mappingApplication, MapPoint.Application).Quit() ' Cast to base type.
            _mappingApplication = Nothing
        End If

        MyBase.Finalize()

    End Sub


    '
    '
    '
    Private Sub initMapControl()

        Try

            If mappingMap IsNot Nothing Then
                _mappingMap.Saved = True  ' Forestall the "Save Changes?" dialog
                _mappingMap = Nothing
            End If

            mapLocationControl.NewMap(MapPoint.GeoMapRegion.geoMapNorthAmerica)

            mappingApplication = mapLocationControl.ActiveMap.Application
            mappingMap = mappingApplication.ActiveMap

            mappingMap.MapStyle = MapPoint.GeoMapStyle.geoMapStyleRoad

            mappingApplication.ShowNavigation = False

            Dim strAddress As String = Nothing
            Dim mapSA As MapPoint.StreetAddress = Nothing


            'POINT (-87.627789974212646 41.882023079055145)
            mappingLocation = mappingControl.ActiveMap.GetLocation(41.882023079055145, -87.627789974212646, 10)
            mappingLocation.GoTo()




        Catch com As COMException
            ' add com exception handler here
            '********* visio snippet vb.net vis0056vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(com, "Com+ Policy")
            If (rethrow) Then
                Throw
            End If

        Catch ex As Exception
            ' add exception handler here
            '********* visio snippet vb.net vis0059vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If

        End Try
    End Sub

#End Region

#Region " Visio/Drawing Control Events "

    '
    ' capture the mouse up event from the visio window
    '
    Private Sub mouseUp_EventHandler(ByVal mouseButton As Integer, _
                ByVal buttonState As Integer, _
                ByVal clickLocationX As Double, _
                ByVal clickLocationY As Double, _
                ByRef cancelProcessing As Boolean)

        Const tolerance As Double = 0.0001

        Dim clickedShapes As Microsoft.Office.Interop.Visio.Selection = Nothing
        Dim message As New System.Text.StringBuilder()
        ' Get the list of shapes at the click location.
        Dim visPage As Microsoft.Office.Interop.Visio.Page = Nothing

        Try

            ' Check if the left mouse mouseButton caused this event
            ' to occur.
            If mouseButton = CInt(Microsoft.Office.Interop.Visio. _
                VisKeyButtonFlags.visMouseLeft) Then


                Try
                    visPage = drawingPage
                Catch
                End Try
                If visPage Is Nothing Then
                    Throw New System.ArgumentNullException("visioPage", _
                            "drawingPage is Null.")
                End If

                Try
                    clickedShapes = getMouseClickShapes( _
                        visPage, clickLocationX, _
                        clickLocationY, tolerance)
                Catch
                End Try

                If clickedShapes Is Nothing Then Exit Sub

                ' Check if any shapes were found.
                If 0 < clickedShapes.Count Then


                    If clickedShapes.Item(1).CellExists("user.attrkey", False) = True Then
                        Dim strAttrCell As String = clickedShapes.Item(1).Cells("user.attrkey").ResultStr("")
                        ' Show the name of shape.
                        message.Append(strAttrCell & _
                            System.Environment.NewLine)

                        ' parse out the shape name
                        ' first string is the record field name
                        ' second string is the record key
                        Dim visShape As Microsoft.Office.Interop.Visio.Shape = clickedShapes.Item(1)


                        Dim returnValue As String()
                        returnValue = strAttrCell.Split({"_"c}, _
                                2, StringSplitOptions.None)


                        If returnValue(0) = "rckCompKey" Then

                            If visShape.CellExists("prop.rckurri", False) = True Then
                                Dim strUrri As String = visShape.Cells("prop.rckurri").ResultStr("")


                                Dim csvValue As String()
                                strUrri = strUrri.Replace("[", "")
                                strUrri = strUrri.Replace("]", "")
                                csvValue = strUrri.Split({","c}, _
                                        5, StringSplitOptions.None)

                                ' create a urri object 
                                Dim newUrri As rackURRI = New rackURRI
                                newUrri.clientKey = CInt(csvValue(0))
                                newUrri.locKey = CInt(csvValue(1))
                                newUrri.attrlocKey = CInt(csvValue(2))
                                newUrri.rowKey = CInt(csvValue(3))
                                newUrri.rckKey = CInt(csvValue(4))

                                ' add it to the selected rack list
                                addUrriToListView(newUrri, Me.lvwSelectedRacks)
                                ' save it as last urri
                                LastUrri = newUrri
                                ' make sure it is highlighted
                                highlightSelectedRacks()

                            End If ' test rckurri

                        End If ' test rckcomp

                    End If ' attrkey


                    'If (drawingWindow.Application.AlertResponse = 0) Then
                    'System.Windows.Forms.MessageBox.Show(message.ToString)
                    'drawingWindow.DeselectAll()
                    'End If

                End If
            End If

        Catch com As COMException
            '********* visio snippet vb.net vis0056vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(com, "Com+ Policy")
            If (rethrow) Then
                Throw
            End If

        Catch ex As Exception
            '********* visio snippet vb.net vis0059vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try

    End Sub

    '
    ' find the shape that was acted on, in the event that it was a list determine which
    ' item was in tolerance
    '
    Private Shared Function getMouseClickShapes( _
                ByVal clickedPage As Microsoft.Office.Interop.Visio.Page, _
                ByVal clickedLocationX As Double, _
                ByVal clickedLocationY As Double, _
                ByVal tolerance As Double) _
                As Microsoft.Office.Interop.Visio.Selection



        Dim returnedSelection As Microsoft.Office.Interop.Visio.Selection = Nothing
        Dim strContainerType As String = ""
        Dim visContainer As Microsoft.Office.Interop.Visio.Shape = Nothing

        Dim dblHeight As Double = 0
        Dim dblWidth As Double = 0

        Dim dblLeft As Double = 0
        Dim dblTop As Double = 0
        Dim dblBottom As Double = 0
        Dim dblRight As Double = 0

        Try

            ' Use the SpatialSearch method of the page to get the list
            ' of shapes at the location.
            Dim clickedShapes As Microsoft.Office.Interop.Visio.Selection = Nothing
            clickedShapes = clickedPage.SpatialSearch( _
                clickedLocationX, clickedLocationY, _
                CInt(Microsoft.Office.Interop.Visio. _
                VisSpatialRelationCodes.visSpatialContainedIn), _
                tolerance, _
                CInt(Microsoft.Office.Interop.Visio.VisSpatialRelationFlags.visSpatialIncludeContainerShapes + _
                    Microsoft.Office.Interop.Visio.VisSpatialRelationFlags.visSpatialFrontToBack))

            If clickedShapes.Count < 1 Then Return returnedSelection

            ' if the clicked shapes has a container shape, then we have to chase down the members
            Dim visShape As Microsoft.Office.Interop.Visio.Shape = Nothing
            Dim visSubShape As Microsoft.Office.Interop.Visio.Shape = Nothing
            Const strContFlag As String = "user.msvStructureType"
            Dim colList As Collection = Nothing
            Dim intX As Integer
            ' walk through the selection objects
            For intX = 1 To clickedShapes.Count
                visContainer = clickedShapes(intX)
                If visContainer.CellExists(strContFlag, VisExistsFlags.visExistsAnywhere) = True Then
                    Dim colTemp As Collection = New Collection
                    strContainerType = LCase(visContainer.Cells(strContFlag).ResultStr(""))
                    'get a list of shapeids in the list
                    If strContainerType = "list" Then
                        For Each memberID In visContainer.ContainerProperties.GetListMembers
                            colTemp.Add(memberID.ToString)
                        Next
                    End If ' the shape type is a list
                    If strContainerType = "container" Then
                        For Each memberID In visContainer.ContainerProperties.GetMemberShapes(VisContainerFlags.visContainerFlagsDefault)
                            colTemp.Add(memberID.ToString)
                        Next
                    End If ' the shape type is a list

                    If 0 < colTemp.Count Then
                        For Each shapeid In colTemp
                            visShape = clickedPage.Shapes.ItemFromID(shapeid)
                            ' assuming that pinx/piny are centered in shape
                            dblHeight = visShape.Cells("height").ResultIU
                            dblWidth = visShape.Cells("width").ResultIU
                            dblLeft = visShape.Cells("pinx").ResultIU - (dblWidth * 0.5)
                            dblRight = visShape.Cells("pinx").ResultIU + (dblWidth * 0.5)
                            dblTop = visShape.Cells("piny").ResultIU + (dblHeight * 0.5)
                            dblBottom = visShape.Cells("piny").ResultIU - (dblHeight * 0.5)

                            If (dblLeft <= clickedLocationX) _
                                And (clickedLocationX <= dblRight) _
                                And (dblBottom <= clickedLocationY) _
                                And (clickedLocationY <= dblTop) Then
                                ' if we are in a container/list shape then we are done
                                clickedShapes.DeselectAll()
                                returnedSelection = clickedPage.CreateSelection(VisSelectionTypes.visSelTypeSingle, VisSelectMode.visSelModeSkipSuper, visShape)
                                ' do not need to look for more 
                                Exit For
                            End If ' test the size
                        Next shapeid
                    End If ' test for coltemp count
                End If ' test for container flags

            Next intX ' loop returned shapes

        Catch com As COMException
            '********* visio snippet vb.net vis0056vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(com, "Com+ Policy")
            If (rethrow) Then
                Throw
            End If

        Catch ex As Exception
            '********* visio snippet vb.net vis0059vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try


        Return returnedSelection

    End Function


#End Region

#Region " MapControl Events "


    '
    ' get the latitude and longitude of the mouse click
    '
    Private Sub mapLocationControl_MouseUpEvent(ByVal sender As Object, ByVal e As AxMapPoint._IMappointCtrlEvents_MouseUpEvent) Handles mapLocationControl.MouseUpEvent

        Try

            Dim x As Integer = CInt(e.x)
            Dim y As Integer = CInt(e.y)

            Dim dblLat As Double = 0
            Dim dblLon As Double = 0

            Dim mapLoc As MapPoint.Location = mappingMap.XYToLocation(x, y)

            CalcPos(mappingMap, mapLoc, dblLat, dblLon)

            Me.lblLatitude.Text = dblLat.ToString
            Me.lblLongitude.Text = dblLon.ToString


        Catch ex As Exception
            ' add exception handler here
            '********* visio snippet vb.net vis0059vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try

    End Sub



#End Region

#Region " Drawing Methods "

    '
    ' create a wan page and place a map shape on it, save the position information as 
    ' shape data
    '
    Private Function addVisioMapToDocument _
                (ByVal strMapMaster As String, _
                 Optional ByVal strMapMasterName As String = "MapName", _
                 Optional ByVal dblScaleSize As Double = 1.0) _
                As Microsoft.Office.Interop.Visio.Shape

        ' To convert latitude and longitude values from degree-minute-second 
        ' (DMS) to decimal format, you can use this formula: 
        ' degrees(+(minutes * 1 / 60) + (seconds * 1 / 3600))


        Dim shpReturn As Microsoft.Office.Interop.Visio.Shape = Nothing

        Try

            drawingWindow.ShowGrid = False

            ' add a map page 
            Dim mapPage As Microsoft.Office.Interop.Visio.Page = Nothing
            Try
                mapPage = drawingApplication.ActiveDocument.Pages("WanDrawing")
            Catch ex As Exception
            End Try
            If mapPage Is Nothing Then
                mapPage = drawingDocument.Pages.Add()
                mapPage.NameU = "WanDrawing"
                mapPage.Name = "WanDrawing"
                mapPage.Background = False
            End If

            drawingWindow.Page = mapPage
            drawingPage = mapPage
            ' make sure the pages are in sync
            _clsVisio.drawingPage = mapPage

            Dim visPageSheet As Microsoft.Office.Interop.Visio.Shape = mapPage.PageSheet
            visPageSheet.Cells("DrawingScale").Formula = My.Settings.drwDrawingScale
            visPageSheet.Cells("PageScale").Formula = My.Settings.drwPageScaleSingle
            visPageSheet.Cells("PageWidth").Formula = My.Settings.drwPageWidthSingle
            visPageSheet.Cells("PageHeight").Formula = My.Settings.drwPageHeightSingle
            visPageSheet.Cells("RouteStyle").Formula = "2"

            System.Windows.Forms.Application.DoEvents()

            Dim visMap As Microsoft.Office.Interop.Visio.Shape = Nothing
            ' get the stencil name from settings
            Dim strStencil As String = My.Settings.us_map_stencil
            ' add the stencil path to the stencil name
            strStencil = My.Settings.path_default_stencils & strStencil

            _clsVisio.visioOpenStencil(drawingApplication, strStencil, VisOpenSaveArgs.visOpenHidden)
            Dim blnLoaded As Boolean = _clsVisio.TestStencilLoaded(drawingApplication, My.Settings.us_map_stencil)
            If blnLoaded = False Then
                MsgBox("Unable to load stencil " & strStencil)
                Return Nothing
            End If
            Try
                visMap = _clsVisio.DropMasterOnPage(mapPage, strMapMaster, strStencil, 0, 0, VisUnitCodes.visInches)
            Catch
            End Try
            If visMap Is Nothing Then
                MsgBox("Unable to load map master " & strMapMaster)
                Return Nothing
            End If

            visMap.NameU = strMapMasterName
            visMap.Name = strMapMasterName

            Dim dblMapWidth As Double = visMap.Cells("Width").ResultIU * dblScaleSize
            Dim dblMapHeight As Double = visMap.Cells("Height").ResultIU * dblScaleSize

            visMap.Cells("Width").Formula = dblMapWidth
            visMap.Cells("Height").Formula = dblMapHeight

            Dim strUserMap As String = ""
            ' need to parse out the latitude and longitude to user fields
            If visMap.CellExists("user.mapdata", VisExistsFlags.visExistsAnywhere) = True Then

                strUserMap = visMap.Cells("user.mapdata").ResultStr("")

                Dim returnValue As String()
                returnValue = strUserMap.Split({"|"c}, _
                        5, StringSplitOptions.None)


                Dim iRow As Integer
                If visMap.SectionExists(VisSectionIndices.visSectionProp, VisExistsFlags.visExistsAnywhere) = 0 Then
                    visMap.AddSection(VisSectionIndices.visSectionProp)
                End If

                If visMap.CellExistsU("Prop.MinLat", VisExistsFlags.visExistsAnywhere) = 0 Then
                    iRow = visMap.AddNamedRow(VisSectionIndices.visSectionProp, "MinLat", 0)
                    visMap.CellsSRC(VisSectionIndices.visSectionProp, iRow, VisCellIndices.visCustPropsLabel).Formula = "=""Min Latitude"""
                    visMap.CellsSRC(VisSectionIndices.visSectionProp, iRow, VisCellIndices.visCustPropsType).Formula = "=2"
                Else
                    iRow = visMap.Cells("Prop.MinLat").Row
                End If
                visMap.CellsSRC(VisSectionIndices.visSectionProp, iRow, VisCellIndices.visCustPropsValue).Formula = "=" & returnValue(1)

                If visMap.CellExistsU("Prop.MinLon", VisExistsFlags.visExistsAnywhere) = 0 Then
                    iRow = visMap.AddNamedRow(VisSectionIndices.visSectionProp, "MinLon", 0)
                    visMap.CellsSRC(VisSectionIndices.visSectionProp, iRow, VisCellIndices.visCustPropsLabel).Formula = "=""Min Longitude"""
                    visMap.CellsSRC(VisSectionIndices.visSectionProp, iRow, VisCellIndices.visCustPropsType).Formula = "=2"
                Else
                    iRow = visMap.Cells("Prop.MinLon").Row
                End If
                visMap.CellsSRC(VisSectionIndices.visSectionProp, iRow, VisCellIndices.visCustPropsValue).Formula = "=" & returnValue(2)

                If visMap.CellExistsU("Prop.MaxLat", VisExistsFlags.visExistsAnywhere) = 0 Then
                    iRow = visMap.AddNamedRow(VisSectionIndices.visSectionProp, "MaxLat", 0)
                    visMap.CellsSRC(VisSectionIndices.visSectionProp, iRow, VisCellIndices.visCustPropsLabel).Formula = "=""Max Latitude"""
                    visMap.CellsSRC(VisSectionIndices.visSectionProp, iRow, VisCellIndices.visCustPropsType).Formula = "=2"
                Else
                    iRow = visMap.Cells("Prop.MaxLat").Row
                End If
                visMap.CellsSRC(VisSectionIndices.visSectionProp, iRow, VisCellIndices.visCustPropsValue).Formula = "=" & returnValue(3)


                If visMap.CellExistsU("Prop.MaxLon", VisExistsFlags.visExistsAnywhere) = 0 Then
                    iRow = visMap.AddNamedRow(VisSectionIndices.visSectionProp, "MaxLon", 0)
                    visMap.CellsSRC(VisSectionIndices.visSectionProp, iRow, VisCellIndices.visCustPropsLabel).Formula = "=""Max Longitude"""
                    visMap.CellsSRC(VisSectionIndices.visSectionProp, iRow, VisCellIndices.visCustPropsType).Formula = "=2"
                Else
                    iRow = visMap.Cells("Prop.MaxLon").Row
                End If
                visMap.CellsSRC(VisSectionIndices.visSectionProp, iRow, VisCellIndices.visCustPropsValue).Formula = "=" & returnValue(0)

                Dim dblZoom As Double = CDbl(returnValue(4))

                ' guard the map so it cannot be moved since the referenced shapes do not use
                ' it as their pinx/piny source
                Dim strPinX As String = CStr(visPageSheet.Cells("PageWidth").ResultIU * 0.5)
                'strPinX = "GUARD(" & strPinX & ")"
                visMap.Cells("PinX").Formula = strPinX
                Dim strPinY As String = CStr(visPageSheet.Cells("PageHeight").ResultIU * 0.5)
                'strPinY = "GUARD(" & strPinY & ")"
                visMap.Cells("PinY").Formula = strPinY

            Else
                MsgBox(" No User.MapData in master shape ", MsgBoxStyle.Exclamation, "Shape Error")
                Return Nothing
            End If ' test for map data

            shpReturn = visMap

        Catch com As COMException
            '********* visio snippet vb.net vis0056vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(com, "Com+ Policy")
            If (rethrow) Then
                Throw
            End If

        Catch ex As Exception
            ' add exception handler here
            '********* visio snippet vb.net vis0059vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If

        End Try

        Return shpReturn

    End Function

    '
    ' pass in the map shape, the pasted map shape, and the map position then move
    ' the pasted image
    ' adjust numbers for the US so that we are working with positives
    '
    Private Sub moveShapeToLongitudeLatitudeOnVisioMap _
                (ByRef visMapShape As Microsoft.Office.Interop.Visio.Shape, _
                 ByRef visNewShape As Microsoft.Office.Interop.Visio.Shape, _
                 ByVal dblLongitude As Double, _
                 ByVal dblLatitude As Double)


        Try

            Dim dblIPDLon As Double = 0
            Dim dblIPDLat As Double = 0
            Dim dblMapWidth As Double = visMapShape.Cells("Width").ResultIU
            Dim dblMapHeight As Double = visMapShape.Cells("Height").ResultIU
            Dim dblMaxLon As Double = visMapShape.Cells("prop.maxlon").ResultIU * -1
            Dim dblMinLon As Double = visMapShape.Cells("prop.minlon").ResultIU * -1
            Dim dblMaxLat As Double = visMapShape.Cells("prop.maxlat").ResultIU
            Dim dblMinLat As Double = visMapShape.Cells("prop.minlat").ResultIU

            dblIPDLon = dblMapWidth / (dblMaxLon - dblMinLon)
            dblIPDLat = dblMapHeight / (dblMaxLat - dblMinLat)

            ' test illinois map lower left
            'dblLongitude = -91.505943
            'dblLatitude = 36.967792
            ' test illinois map top right
            'dblLongitude = -87.496338
            'dblLatitude = 42.506908

            ' shift from map start (lower left of shape)
            Dim dblLonDeg = (dblMaxLon - (dblLongitude * -1)) * dblIPDLon
            Dim dblLatDeg = (dblLatitude - dblMinLat) * dblIPDLat

            Dim dblLowWidth = visMapShape.Cells("PinX").ResultIU - visMapShape.Cells("LocPinX").ResultIU
            Dim dblLowHeight = visMapShape.Cells("PinY").ResultIU - visMapShape.Cells("LocPinY").ResultIU

            Dim dblNewPinX As Double = dblLowWidth + dblLonDeg
            Dim dblNewPinY As Double = dblLowHeight + dblLatDeg
            Dim strPinY As String = "GUARD(" & CStr(dblNewPinY) & ")"
            Dim strPinX As String = "GUARD(" & CStr(dblNewPinX) & ")"

            visNewShape.Cells("PinX").Formula = CStr(dblNewPinX)
            visNewShape.Cells("PinY").Formula = CStr(dblNewPinY)


        Catch com As COMException
            '********* visio snippet vb.net vis0056vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(com, "Com+ Policy")
            If (rethrow) Then
                Throw
            End If

        Catch ex As Exception
            ' add exception handler here
            '********* visio snippet vb.net vis0059vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If

        End Try


    End Sub

    '
    ' pass in a page, two shapes, and then use connector with dynamic glue to connect them
    ' we setup routing style in the page creation
    '
    Private Sub connectSitesOnVisioMap _
                (ByVal shpMap As Microsoft.Office.Interop.Visio.Shape,
                ByVal strSiteA As String, _
                 ByVal strSiteB As String)


        Try


            Dim visPage As Microsoft.Office.Interop.Visio.Page = shpMap.ContainingPage
            Dim visShapes As Microsoft.Office.Interop.Visio.Shapes = visPage.Shapes
            Dim visCell As Microsoft.Office.Interop.Visio.Cell = Nothing

            Dim shpSiteA As Microsoft.Office.Interop.Visio.Shape = visShapes(strSiteA)
            Dim shpSiteB As Microsoft.Office.Interop.Visio.Shape = visShapes(strSiteB)
            Dim shpLink As Microsoft.Office.Interop.Visio.Shape = Nothing
            ' make sure the pages are in sync
            _clsVisio.drawingPage = visPage

            Try
                shpLink = _clsVisio.ConnectWithDynamicGlueAndConnector(shpSiteA, shpSiteB)
            Catch
            End Try

            If shpLink IsNot Nothing Then
                Dim linkName As String = strSiteA & " => " & strSiteB
                ' move the name to comment field so we get mouse over
                If shpLink.CellsSRCExists(VisSectionIndices.visSectionObject, VisRowIndices.visRowMisc, VisCellIndices.visComment, False) = True Then
                    visCell = shpLink.CellsSRC(VisSectionIndices.visSectionObject, VisRowIndices.visRowMisc, VisCellIndices.visComment)
                    _clsVisio.SetCellValueToString(visCell, linkName)
                End If
            Else
                Throw New System.ArgumentNullException("ArgumentNullExcepiton", _
                     "Add Link returned null")
            End If


        Catch com As COMException
            '********* visio snippet vb.net vis0056vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(com, "Com+ Policy")
            If (rethrow) Then
                Throw
            End If

        Catch ex As Exception
            ' add exception handler here
            '********* visio snippet vb.net vis0059vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If

        End Try

    End Sub

    '
    ' add location to mappoint, pushpin, the name will be the siteid
    '
    Private Sub syncMapControlToLocation(ByVal intLocKey As Int32)

        Try

            Dim mapLoc As MapPoint.Location = Nothing
            Dim mapFindResults As MapPoint.FindResults = Nothing
            Dim mapPushPin As MapPoint.Pushpin = Nothing

            ' when a location is selected update the map
            Dim strStreet As String = ""
            Dim strCity As String = ""
            Dim strState As String = ""
            Dim strZip As String = ""
            Dim strSite As String = ""

            Dim locationQuery = From location In _clsData.m_ds.Tables(DC_RackTables.tblLocation.ToString).AsEnumerable() _
                       Where location!lockey = intLocKey
                      Select location

            Dim drTemp As System.Data.DataRow = Nothing
            ' we should only have transferred in a single component key
            If locationQuery.Count = 1 Then
                For Each l In locationQuery
                    strStreet = l.Item("locAddress1")
                    strCity = l.Item("locCity")
                    strState = l.Item("locState")
                    strZip = l.Item("locZip").ToString
                    strSite = l.Item("locSiteId")
                Next l
            End If

            ' make sure we only add a pushpin for the site once
            mapPushPin = mappingMap.FindPushpin(strSite)
            If mapPushPin Is Nothing Then

                mappingMap.MapStyle = MapPoint.GeoMapStyle.geoMapStyleRoad
                mapFindResults = mappingMap.FindAddressResults(strStreet, strCity, , strState, strZip, MapPoint.GeoCountry.geoCountryUnitedStates)
                mapLoc = mapFindResults(1)
                mapLoc.GoTo()

                mapPushPin = mappingMap.AddPushpin(AtLocation:=mapLoc, Name:=strSite)
                mapPushPin.BalloonState = MapPoint.GeoBalloonState.geoDisplayBalloon

            Else
                mapLoc = mapPushPin.Location
                mapLoc.GoTo()
            End If

            Dim dblLat As Double = 0
            Dim dblLon As Double = 0

            CalcPos(mappingMap, mapLoc, dblLat, dblLon)

            Me.lblLatitude.Text = dblLat.ToString
            Me.lblLongitude.Text = dblLon.ToString

            'flag the location
            currLocKey = intLocKey


        Catch sql As SqlException
            '********* visio snippet vb.net vis0057vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(sql, "Database Policy")
            If (rethrow) Then
                Throw
            End If
        Catch com As COMException
            ' add com exception handler here
            '********* visio snippet vb.net vis0056vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(com, "Com+ Policy")
            If (rethrow) Then
                Throw
            End If
        Catch ex As Exception
            ' add exception handler here
            '********* visio snippet vb.net vis0059vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If

        End Try

    End Sub

    '
    '
    '
    Private Sub demoAddWanToMappoint()

        'Latitude Required Double. A numerical coordinate that measures how far north (+) 
        'or south (-) of the Equator a place is located, measured in decimal degrees. 
        'Range is 0° to (+/-)90°. For example, "34.33896".

        ' note MapPoint goes to 8 positions of precision, Visio goes to 4 positions, aee

        Try

            initMapControl()

            Dim shpMap As Microsoft.Office.Interop.Visio.Shape = Nothing
            Dim shpSite As Microsoft.Office.Interop.Visio.Shape = Nothing
            Dim strTopologyName As String = "DemoNet"
            shpMap = addVisioMapToDocument("Illinois", strTopologyName, 50)

            Dim strRootSiteId As String = "01001"
            Dim strRootKey As String = "locKey_1"
            Dim strItemKey As String = ""
            Dim locOrigin As MapPoint.Location = Nothing
            Dim locTarget As MapPoint.Location = Nothing
            Dim shpLine As MapPoint.Shape = Nothing
            Dim linkName As String = ""

            Dim pushPinOrigin As MapPoint.Pushpin = Nothing
            Dim pushPinTarget As MapPoint.Pushpin = Nothing

            Dim siteQuery = From location In _clsData.m_ds.Tables(DC_RackTables.tblLocation.ToString).AsEnumerable() _
                 Where location!locclientkey = 1
                Select location

            For Each s In siteQuery
                strItemKey = "locKey_" & CStr(s.Item("locKey"))
                ' put the site on the map
                syncMapControlToLocation(s.Item("locKey"))
                ' the origin should be the first one, so we do not want to try  and
                ' apply a line at this time
                If strItemKey <> strRootKey Then
                    ' we compute latitude and longitude when we put the shape in the map
                    'oLocation3 = mappingMap.GetLocation(CDbl(Me.lblLatitude.Text), CDbl(Me.lblLongitude.Text), 500)
                    pushPinTarget = mappingMap.FindPushpin(s.Item("locSiteId"))
                    pushPinTarget.BalloonState = MapPoint.GeoBalloonState.geoDisplayName
                    locTarget = pushPinTarget.Location
                    locTarget.GoTo()

                    ' snapshot the local geography area so we get a picture and position data
                    shpSite = ImportMap(strItemKey, 0.15)
                    moveShapeToLongitudeLatitudeOnVisioMap(shpMap, shpSite, CDbl(Me.lblLongitude.Text), CDbl(Me.lblLatitude.Text))
                    ' add connection to visio map
                    connectSitesOnVisioMap(shpMap, strRootKey, strItemKey)

                    ' add connection link to mappoint map
                    shpLine = mappingMap.Shapes.AddLine(BeginLocation:=locOrigin, EndLocation:=locTarget)
                    linkName = strRootKey & " => " & strItemKey

                    shpLine.Line.Weight = 5                     ' Pixel
                    shpLine.Line.ForeColor = System.Drawing.KnownColor.Black

                Else
                    pushPinOrigin = mappingMap.FindPushpin(s.Item("locSiteId"))
                    pushPinOrigin.BalloonState = MapPoint.GeoBalloonState.geoDisplayName
                    locOrigin = pushPinOrigin.Location
                    ' move to the site
                    locOrigin.GoTo()
                    ' snapshot the local geography area so we get a picture and position data
                    shpSite = ImportMap(strItemKey, 0.15)
                    moveShapeToLongitudeLatitudeOnVisioMap(shpMap, shpSite, CDbl(Me.lblLongitude.Text), CDbl(Me.lblLatitude.Text))
                End If
            Next s

            ' go to the origin location of the demo network
            mappingMap.MapStyle = MapPoint.GeoMapStyle.geoMapStyleTerrain
            locOrigin.GoTo()

            ' release the last shape 
            drawingWindow.DeselectAll()
            drawingWindow.ViewFit = 1

        Catch com As COMException
            '********* visio snippet vb.net vis0056vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(com, "Com+ Policy")
            If (rethrow) Then
                Throw
            End If

        Catch ex As Exception
            ' add exception handler here
            '********* visio snippet vb.net vis0059vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If

        End Try

    End Sub

    '
    ' pass in a row key and create list items for each of the defined cabinets
    '
    Private Function dropRowCabinetItems _
        (ByVal intRow As Int32) _
        As Microsoft.Office.Interop.Visio.Shape

        ' create a list control
        Dim listControl As Microsoft.Office.Interop.Visio.Shape = Nothing

        Try


            Const constRackAlign As VisListAlignment = VisListAlignment.visListAlignCenterOrMiddle
            Const constRackDir As VisListDirection = VisListDirection.visListDirLeftToRight

            ' this should be setup based on the master used that shows the rack top
            ' but we dummy it up in the demo code
            Const constRackWidth As Double = 20
            Dim strRackWidth As String = CStr(constRackWidth) & "in"

            Dim colInput As Collection = New Collection
            Dim drTemp As System.Data.DataRow = Nothing

            Dim rackQuery = From cabinets In _clsData.m_ds.Tables(DC_RackTables.tblAttrCabinet.ToString).AsEnumerable() _
                      Where cabinets!rckrowKey = intRow _
                      Select cabinets _
                      Order By cabinets!rckRowPos

            Dim intRckPos As Integer = 0

            If 0 < rackQuery.Count Then
                For Each rck In rackQuery
                    colInput.Add("rckCompKey_" & rck.Item("rckCompKey").ToString)
                Next rck
            End If


            ' pass in the created collection and return a populated list control
            Dim colMembers As Collection = New Collection
            Dim strStencil As String = My.Settings.custom_dcrack_stencil
            strStencil = _CustomStencilPath & strStencil
            _clsVisio.drawingPage = drawingPage
            colMembers = _clsVisio.dropDropDownBoxItems(colInput, "cabinettop", strStencil, , )

            Dim visShape As Microsoft.Office.Interop.Visio.Shape = Nothing
            Dim visCell As Microsoft.Office.Interop.Visio.Cell = Nothing
            For Each shapeId In colMembers
                ' get the shape
                visShape = drawingPage.Shapes.ItemFromID(shapeId)
                Dim strName As String = ""
                Dim strKey As String = ""

                If visShape.CellExists("user.attrkey", False) = True Then
                    strKey = visShape.Cells("user.attrkey").ResultStr("")
                    ' go read the current records
                    For Each rck In rackQuery
                        strName = "rckCompKey_" & rck.Item("rckCompKey").ToString
                        If strName = strKey Then
                            ' the rack "name" is usually the grid position that it sits on in the datacenter
                            ' when grid locations are used
                            visShape.Text = rck.Item("rckGrid").ToString
                            _clsVisio.ForceShapeData(visShape, "Comp", "Rack", "AttrCabinet")
                            _clsVisio.ForceShapeData(visShape, "rckKey", rck.Item("rckKey").ToString, "AttrCabinet")
                            _clsVisio.ForceShapeData(visShape, "rckCompKey", strName, "attrCabinet")

                            Dim colKeyURRI As Collection = New Collection
                            colKeyURRI.Add(currClientKey.ToString)
                            colKeyURRI.Add(currLocKey.ToString)
                            colKeyURRI.Add(currSubLocKey.ToString)
                            colKeyURRI.Add(intRow.ToString)
                            colKeyURRI.Add(rck.Item("rckCompKey").ToString)
                            Dim strKeyURRI As String = BuildCsvString(colKeyURRI)

                            _clsVisio.ForceShapeData(visShape, "rckURRI", strKeyURRI, "attrURRI")

                            ' move the attrkey to comment field so we get mouse over
                            If visShape.CellsSRCExists(VisSectionIndices.visSectionObject, VisRowIndices.visRowMisc, VisCellIndices.visComment, False) = True Then
                                visCell = visShape.CellsSRC(VisSectionIndices.visSectionObject, VisRowIndices.visRowMisc, VisCellIndices.visComment)
                                _clsVisio.SetCellValueToString(visCell, strName)
                            End If

                            colKeyURRI = Nothing

                            Exit For
                        End If ' test for name

                    Next rck
                End If ' test for user cell attrkey 

            Next shapeId

            Dim strCtrlName As String = "rowKey_" & intRow.ToString
            listControl = _clsVisio.loadListControl(colMembers, constRackAlign, constRackDir, 0)
            listControl.Name = strCtrlName
            listControl.NameU = strCtrlName


        Catch com As COMException
            ' add com exception handler here
            '********* visio snippet vb.net vis0056vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(com, "Com+ Policy")
            If (rethrow) Then
                Throw
            End If

        Catch ex As Exception
            ' add exception handler here
            '********* visio snippet vb.net vis0059vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If

        End Try

        Return listControl

    End Function

    '
    '
    '
    Private Sub drawRows(ByVal currURRI As rackURRI)

        Try

            Me.GridToolStripMenuItem.Checked = True
            drawingWindow.ShowGrid = True
            currLocKey = currURRI.locKey

            Dim visPageSheet As Microsoft.Office.Interop.Visio.Shape = drawingPage.PageSheet
            If visPageSheet.CellExists("prop.attrlocKey", False) = True Then
                If currURRI.attrlocKey = CInt(visPageSheet.Cells("prop.attrlocKey").ResultIU) Then GoTo DrawComplete
            End If

            ' add the container to hold the list
            Dim shpContainer As Microsoft.Office.Interop.Visio.Shape = Nothing

            ' move to the correct page
            Dim strPageName As String = defaultPageName
            drawingWindow.Page = strPageName
            drawingPage = drawingDocument.Pages(strPageName)
            visPageSheet = drawingPage.PageSheet

            ' add the primary location fields to the page
            _clsVisio.ForceShapeData(visPageSheet, "clientKey", CStr(currURRI.clientKey), "urriKeys")
            _clsVisio.ForceShapeData(visPageSheet, "locKey", CStr(currURRI.locKey), "urriKeys")
            _clsVisio.ForceShapeData(visPageSheet, "attrlocKey", CStr(currURRI.attrlocKey), "urriKeys")

            ' flag the properties
            currClientKey = currURRI.clientKey
            currLocKey = currURRI.locKey
            currSubLocKey = currURRI.attrlocKey


            createLocationGrid(currURRI.attrlocKey)

            Dim intH As Integer = 0
            Dim intW As Integer = 0

            Dim visSelection As Microsoft.Office.Interop.Visio.Selection = Nothing
            Dim intShapes As Integer = drawingPage.Shapes.Count
            If 0 < intShapes Then
                drawingApplication.ActiveWindow.SelectAll()
                visSelection = drawingWindow.Selection
                visSelection.Delete()
            End If

            Dim shpRow As Microsoft.Office.Interop.Visio.Shape = Nothing

            Dim rowQuery = From dcrow In _clsData.m_ds.Tables(DC_RackTables.tblAttrCabinetRow.ToString).AsEnumerable() _
                    Where dcrow!rowloc = currURRI.attrlocKey
                    Select dcrow

            Dim strGrid As String = ""
            Dim strRowId As String = ""
            Dim intRowKey As Int32 = -1
            Dim strRowDirection As String = ""
            Dim intCabCt As Integer = 0
            '
            If 0 < rowQuery.Count Then
                For Each dr In rowQuery
                    intH = 0
                    intW = 0
                    shpRow = Nothing

                    strRowId = LCase(dr.Item("rowId"))

                    strGrid = dr.Item("rowGrid")
                    intRowKey = CInt(dr.Item("rowKey"))
                    strRowDirection = dr.Item("rowOrientation")
                    intCabCt = CInt(dr.Item("rowCabCt"))
                    convertGridLoc(strGrid, intH, intW)
                    'System.Diagnostics.Debug.WriteLine(strRowId & " " & strGrid & " " & CStr(intH) & " " & CStr(intW))
                    If 0 < intH Then
                        shpRow = dropRowCabinetItems(intRowKey)
                        If shpRow IsNot Nothing Then
                            'shpContainer = addContainerToPage("Container 3", strRowId, strRowId)
                            '_clsVisio.ForceShapeData(shpContainer, "compName", strRowId, "attrCabRow")
                            Dim strStartH As String = CStr(intH + (shpRow.Cells("Height").ResultIU * 0.5)) & "in"
                            Dim strStartW As String = CStr(intW + (shpRow.Cells("Width").ResultIU * 0.5)) & "in"
                            shpRow.Cells("pinY").Formula = strStartH
                            shpRow.Cells("pinX").Formula = strStartW
                            'AddShapeToContainer(shpContainer, shpRow)
                        Else
                            System.Diagnostics.Debug.WriteLine("Create row " & CStr(intRowKey) & " failed")
                        End If ' test for returned list shape
                    End If ' test for blank grid position
                    System.Windows.Forms.Application.DoEvents()
                Next dr
            Else
                MsgBox(" No Rows listed for current sublocation ")
            End If


            drawingWindow.DeselectAll()



            ' make sure the page dictionaries have been updated
            initPageDictionaries(drawingApplication.ActivePage)


DrawComplete:
        Catch com As COMException
            ' add com exception handler here
            '********* visio snippet vb.net vis0056vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(com, "Com+ Policy")
            If (rethrow) Then
                Throw
            End If

        Catch ex As Exception
            ' add exception handler here
            '********* visio snippet vb.net vis0059vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If

        End Try


    End Sub

    '
    ' based on the sublocation/attrloc key set grid height and tile size
    '
    Private Sub createLocationGrid(ByVal intAttrLocKey As Int32)

        Try

            Dim sublocationQuery = From sublocation In _clsData.m_ds.Tables(DC_RackTables.tblAttrLocation.ToString).AsEnumerable() _
                    Where sublocation!attrlocKey = intAttrLocKey
                    Select sublocation

            Dim intGridHeight As Integer = 0
            Dim intGridWidth As Integer = 0
            Dim intTileSize As Integer = 0
            If sublocationQuery.Count = 1 Then
                For Each s In sublocationQuery
                    intGridHeight = s.Item("attrlocGridHeight")
                    intGridWidth = s.Item("attrlocGridWidth")
                    intTileSize = s.Item("attrlocGridSize")
                Next s
            End If
            If intGridHeight < 1 _
                Or intGridWidth < 1 _
                Or intTileSize < 1 Then
                Exit Sub
            Else
                setupPageGrid(drawingPage, intGridHeight, intGridWidth, intTileSize)
                Dim pageSheet As Microsoft.Office.Interop.Visio.Shape = drawingPage.PageSheet
                ' route the lines directly instead of right angle
                pageSheet.Cells("RouteStyle").Formula = "2"
                _clsVisio.ForceUserProperty(pageSheet, "subLocKey", CStr(intAttrLocKey))
            End If


        Catch sql As SqlException
            '********* visio snippet vb.net vis0057vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(sql, "Database Policy")
            If (rethrow) Then
                Throw
            End If
        Catch com As COMException
            ' add com exception handler here
            '********* visio snippet vb.net vis0056vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(com, "Com+ Policy")
            If (rethrow) Then
                Throw
            End If

        Catch ex As Exception
            ' add exception handler here
            '********* visio snippet vb.net vis0059vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If

        End Try


    End Sub

    '
    ' pass in a grid location and update the referenced x/y coordinates that are pointed to
    '
    Private Sub convertGridLoc _
        (ByVal strGridLoc As String, _
         ByRef intGridHeight As Integer, _
         ByRef intGridWidth As Integer)


        Try

            intGridHeight = -1
            intGridWidth = -1

            ' some locations explicitly exclude characters like "I" and "O" because of similarities
            ' to numbers
            Const strValidAlpha As String = "abcdefghijklmnopqrstuvwxyz"

            Dim intX As Integer = 0
            Dim intFirstAlpha As Integer = -1
            Dim strAlpha As String = ""
            Dim strTemp As String = ""
            Dim intFirstNumber As Integer = -1
            Dim strNumber As String = ""
            Dim charCurrent As Char

            Dim pageSheet As Microsoft.Office.Interop.Visio.Shape = drawingPage.PageSheet
            Dim intPageWidth As Integer = pageSheet.Cells("PageWidth").ResultInt(VisUnitCodes.visInches, VisRoundFlags.visTruncate)
            Dim intPageHeight As Integer = pageSheet.Cells("PageHeight").ResultInt(VisUnitCodes.visInches, VisRoundFlags.visTruncate)
            Dim intTileSize As Integer = pageSheet.Cells("XGridSpacing").ResultInt(VisUnitCodes.visInches, VisRoundFlags.visTruncate)

            ' find first alpha
            For intX = 0 To Len(strGridLoc) - 1
                charCurrent = CChar(strGridLoc.Substring(intX, 1))
                If charCurrent.IsLetter(strGridLoc, intX) = True Then
                    If intFirstAlpha < 0 Then
                        intFirstAlpha = intX
                        Exit For
                    End If
                End If
            Next intX

            If 0 <> intFirstAlpha Then
                MsgBox("Grid location must be alpha first position")
                Exit Sub
            End If

            ' find first numeric
            For intX = 0 To Len(strGridLoc) - 1
                charCurrent = CChar(strGridLoc.Substring(intX, 1))
                If charCurrent.IsNumber(strGridLoc, intX) = True Then
                    If intFirstNumber < 0 Then
                        intFirstNumber = intX
                        Exit For
                    End If
                End If
            Next intX

            ' if invalid format then get out (no numeric)
            If intFirstNumber < 0 Then
                Exit Sub
            End If

            strAlpha = LCase(strGridLoc.Substring(0, intFirstNumber))
            strNumber = strGridLoc.Substring(intFirstNumber)

            ' the number is easy to check do it first
            If CInt(strNumber) <= (intPageWidth / intTileSize) _
                And 0 < CInt(strNumber) Then
                intGridWidth = (CInt(strNumber) * intTileSize) - intTileSize
            Else
                MsgBox(" Grid Loc number is out of range ")
                Exit Sub
            End If

            ' test for invalid characters
            For intX = 0 To Len(strAlpha) - 1
                strTemp = strAlpha.Substring(intX, 1)
                If strValidAlpha.Contains(strTemp) = False Then
                    MsgBox(" GridLoc Alpha contains invalid character ")
                    Exit Sub
                End If
            Next intX

            Dim tempTiles As Integer = 0
            Dim intY As Integer
            For intX = Len(strAlpha) - 1 To 0 Step -1
                Select Case intX
                    Case 0
                        charCurrent = strAlpha.Chars(intX)
                        tempTiles = tempTiles + strValidAlpha.IndexOf(charCurrent) * Len(strValidAlpha)
                    Case 1
                        charCurrent = strAlpha.Chars(intX)
                        intY = (strValidAlpha.IndexOf(charCurrent) + 1)
                        tempTiles = tempTiles + intY
                End Select
            Next (intX)

            intGridHeight = tempTiles * intTileSize

        Catch com As COMException
            ' add com exception handler here
            '********* visio snippet vb.net vis0056vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(com, "Com+ Policy")
            If (rethrow) Then
                Throw
            End If

        Catch ex As Exception
            ' add exception handler here
            '********* visio snippet vb.net vis0059vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If

        End Try



    End Sub

    '
    ' setup page size based on tile sizes, default 60ft x 40ft
    ' pass in attrlocGridHeight, attrlocGridWidth, attrlocGridSize as integers
    '
    Private Sub setupPageGrid _
        (ByVal visPage As Microsoft.Office.Interop.Visio.Page, _
         Optional ByVal intGridHeight As Integer = 30, _
         Optional ByVal intGridWidth As Integer = 20, _
         Optional ByVal intTileSize As Integer = 24)


        Try

            Dim visLayers As Microsoft.Office.Interop.Visio.Layers = Nothing
            Dim visLayer As Microsoft.Office.Interop.Visio.Layer = Nothing

            visLayers = visPage.Layers
            _clsVisio.AddLayerToPage(visPage, connectedlayerNameU)
            _clsVisio.AddLayerToPage(visPage, selectedLayerNameU)
            Dim pagCell As Microsoft.Office.Interop.Visio.Cell
            pagCell = visPage.PageSheet.Cells("layers.color[1]")
            _clsVisio.SetCellValueToString(pagCell, VisDefaultColors.visDarkGreen)
            pagCell = visPage.PageSheet.Cells("layers.color[2]")
            _clsVisio.SetCellValueToString(pagCell, VisDefaultColors.visDarkRed)


            Dim pageSheet As Microsoft.Office.Interop.Visio.Shape = visPage.PageSheet
            pageSheet.CellsSRC(VisSectionIndices.visSectionObject, VisRowIndices.visRowPage, _
                                VisCellIndices.visPageWidth).Formula = CStr(intGridWidth * intTileSize)
            pageSheet.CellsSRC(VisSectionIndices.visSectionObject, VisRowIndices.visRowPage, _
                                VisCellIndices.visPageHeight).Formula = CStr(intGridHeight * intTileSize)

            pageSheet.CellsSRC(VisSectionIndices.visSectionObject, VisRowIndices.visRowPage, _
                    VisCellIndices.visPageScale).Formula = ".375in"
            pageSheet.CellsSRC(VisSectionIndices.visSectionObject, VisRowIndices.visRowPage, _
                    VisCellIndices.visPageDrawingScale).Formula = "1ft"
            pageSheet.CellsSRC(VisSectionIndices.visSectionObject, VisRowIndices.visRowPage, _
                    VisCellIndices.visPageDrawScaleType).Formula = "0"

            ' visSectionObject, visRowRulerGrid
            pageSheet.CellsSRC(VisSectionIndices.visSectionObject, VisRowIndices.visRowRulerGrid, _
                                VisCellIndices.visXGridOrigin).Formula = "0"
            pageSheet.CellsSRC(VisSectionIndices.visSectionObject, VisRowIndices.visRowRulerGrid, _
                                VisCellIndices.visYGridOrigin).Formula = "0"

            pageSheet.CellsSRC(VisSectionIndices.visSectionObject, VisRowIndices.visRowRulerGrid, _
                                VisCellIndices.visXGridDensity).Formula = "0"
            pageSheet.CellsSRC(VisSectionIndices.visSectionObject, VisRowIndices.visRowRulerGrid, _
                                VisCellIndices.visYGridDensity).Formula = "0"

            pageSheet.CellsSRC(VisSectionIndices.visSectionObject, VisRowIndices.visRowRulerGrid, _
                                VisCellIndices.visXGridSpacing).Formula = intTileSize.ToString & "in"
            pageSheet.CellsSRC(VisSectionIndices.visSectionObject, VisRowIndices.visRowRulerGrid, _
                                VisCellIndices.visYGridSpacing).Formula = intTileSize.ToString & "in"

            drawingWindow.Page = visPage.Name

            _clsVisio.ForceUserProperty(pageSheet, "subLocKey", "-1")



        Catch com As COMException
            ' add com exception handler here
            '********* visio snippet vb.net vis0056vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(com, "Com+ Policy")
            If (rethrow) Then
                Throw
            End If

        Catch ex As Exception
            ' add exception handler here
            '********* visio snippet vb.net vis0059vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If

        End Try
    End Sub

    '
    ' pass in a shape and then zoom the window to show it
    '
    Private Sub searchZoomObject(ByVal visShape As Microsoft.Office.Interop.Visio.Shape)


        Try

            drawingWindow.Select(visShape, 2)
            ' make the size larger so we have a margin around the shape
            Dim dblHeight As Double = visShape.Cells("height").ResultIU * 1.1
            Dim dblWidth As Double = visShape.Cells("width").ResultIU * 1.1
            Dim dblLeft As Double = visShape.Cells("pinx").ResultIU - (dblWidth * 0.5)
            Dim dblTop As Double = visShape.Cells("piny").ResultIU + (dblHeight * 0.5)


            drawingWindow.SetViewRect(dblLeft, dblTop, dblWidth, dblHeight)



        Catch com As COMException
            ' add com exception handler here
            '********* visio snippet vb.net vis0056vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(com, "Com+ Policy")
            If (rethrow) Then
                Throw
            End If

        Catch ex As Exception
            ' add exception handler here
            '********* visio snippet vb.net vis0059vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If

        End Try

    End Sub

    ' 
    ' build two shapeid dictionaries for the passed in page, one for
    ' components and one for links.
    ' This routine allows us to search for shapes without having to
    ' continually cross the com+ boundary
    '
    Public Sub initPageDictionaries(ByVal visPage As Visio.Page)


        Try

            If Not (m_dictComponents Is Nothing) Then
                m_dictComponents = Nothing
            End If
            m_dictComponents = New Dictionary(Of Integer, String)

            If Not (m_dictLinks Is Nothing) Then
                m_dictLinks = Nothing
            End If
            m_dictLinks = New Dictionary(Of Integer, String)

            If Not (m_dictConnected Is Nothing) Then
                m_dictConnected = Nothing
            End If
            m_dictConnected = New Dictionary(Of Integer, String)


            Dim idShape As Integer
            Dim visShape As Visio.Shape
            Dim layerCount As Integer
            Dim layerInPage As Microsoft.Office.Interop.Visio.Layer = Nothing
            Dim currentLayerName As String = ""
            Dim strName As String = ""
            If Not (visPage Is Nothing) Then
                For Each visShape In visPage.Shapes
                    ' only interested in shapes that have our user flag and key
                    If visShape.CellExists("user.attrkey", False) = True Then
                        strName = visShape.Cells("user.attrkey").ResultStr("")
                    Else
                        GoTo NextShape
                    End If
                    ' get the shapeID for our key in the dictionary 
                    idShape = visShape.ID
                    ' test to see if it is a link 
                    If visShape.CellExists("prop.linkName", False) = True Then
                        If m_dictLinks.ContainsKey(idShape) = False Then
                            m_dictLinks.Add(idShape, strName)
                        End If
                    End If
                    ' get the rack names

                    If visShape.CellExists("prop.rckCompKey", False) = True Then
                        If m_dictComponents.ContainsKey(idShape) = False Then
                            m_dictComponents.Add(idShape, strName)
                            ' check to see if it is on the connected shapes layer
                            layerCount = visShape.LayerCount
                            If 0 < layerCount Then
                                ' Iterate through all the layers for that shape.
                                For layerIndex = 1 To layerCount
                                    ' Check if the shape is in the specified layer.
                                    layerInPage = visShape.Layer(layerIndex)
                                    currentLayerName = layerInPage.NameU
                                    If currentLayerName <> selectedLayerNameU _
                                        And currentLayerName <> connectedlayerNameU Then
                                        _clsVisio.RemoveShapeFromLayer(drawingPage, visShape, currentLayerName, True)
                                    End If
                                    If (currentLayerName = connectedlayerNameU) Then
                                        m_dictConnected.Add(idShape, strName)
                                    End If ' test for layer in shape
                                Next layerIndex
                            End If ' test for layer count
                        End If
                    End If
NextShape:
                Next visShape
            End If

            'Debug.Print("dictionary counts " & dictComponents.Count & " " & dictLinks.Count)

        Catch com As COMException
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(com, "Com+ Policy")
            If (rethrow) Then
                Throw
            End If
        Catch err As Exception
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(err, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try

    End Sub

    '
    ' pass in a rackURRI and get a collection of connected racks
    '
    Private Function getConnectedRackList _
        (ByVal intRack As Int32) _
        As Collection(Of clsDC_RackData.rackURRI)

        Dim colReturn As Collection(Of clsDC_RackData.rackURRI) = New Collection(Of clsDC_RackData.rackURRI)


        Try

            Dim m_clsNetworkLinks As clsNetworkLinks = New clsNetworkLinks(drawingApplication, drawingDocument)
            Dim m_clsCabinets As clsAttrCabinet = New clsAttrCabinet
            Dim rckURRI As clsDC_RackData.rackURRI


            Dim colRacks As Collection = New Collection
            m_clsNetworkLinks.dbSelectNetworkLinksByRackKey(intRack)

            Dim rackQuery = From dr_links In m_clsNetworkLinks.m_tempdt.AsEnumerable() _
                Select dr_links
            'execute
            Dim lngRackKey As Int32
            For Each p In rackQuery
                lngRackKey = p.Field(Of Int32)("vwlocRackACompKey")
                If colRacks.Contains(CStr(lngRackKey)) = False Then
                    colRacks.Add(lngRackKey, CStr(lngRackKey))
                End If
                lngRackKey = p.Field(Of Int32)("vwlocRackBCompKey")
                If colRacks.Contains(CStr(lngRackKey)) = False Then
                    colRacks.Add(lngRackKey, CStr(lngRackKey))
                End If
            Next
            ' take out the source rack
            If colRacks.Contains(CStr(intRack)) Then
                colRacks.Remove(CStr(intRack))
            End If

            ' now walk the collection of racks and get their urris
            Dim lngRack As Int32
            Dim strRackUrri As String = ""
            Dim dtTemp As System.Data.DataTable
            Dim drTemp As System.Data.DataRow
            For Each lngRack In colRacks
                dtTemp = m_clsCabinets.dbSelectCabinetViewByRackKey(lngRack)

                'execute
                If 0 < dtTemp.Rows.Count Then
                    For Each drTemp In dtTemp.Rows
                        rckURRI = Nothing
                        rckURRI = New clsDC_RackData.rackURRI
                        With drTemp
                            rckURRI.clientKey = .Field(Of Int32)("vwcabClientKey")
                            rckURRI.rckKey = .Field(Of Int32)("compKey")
                            rckURRI.locKey = .Field(Of Int32)("vwcabSiteKey")
                            rckURRI.attrlocKey = .Field(Of Int32)("vwcabLocKey")
                            rckURRI.rowKey = .Field(Of Int32)("vwcabRowKey")
                        End With

                        colReturn.Add(rckURRI)
                    Next
                End If
            Next lngRack

        Catch sql As SqlException
            '********* visio snippet vb.net vis0057vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(sql, "Database Policy")
            If (rethrow) Then
                Throw
            End If
        Catch ex As Exception
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try

        Return colReturn


    End Function
    '
    ' pass in a source rack and targetlist of racks, add the shapes to the connected layer
    ' and then add dynamic connectors between them
    '
    Private Sub showConnectedRackList _
                (ByVal rlSource As clsDC_RackData.rackURRI, _
                 ByVal rlTargets As Collection(Of clsDC_RackData.rackURRI))

        Try

            'make sure the grid page is the active page
            drawingPage = drawingDocument.Pages(defaultPageName)
            drawingWindow.Page = drawingPage.Name
            ' make sure the visio helper is in the right place
            _clsVisio.drawingPage = drawingPage
            ' build a dictionary of shapeids and links
            initPageDictionaries(drawingPage)
            Dim layerInPage As Microsoft.Office.Interop.Visio.Layer = Nothing

            ' Check if the layer exists.
            Try
                layerInPage = drawingPage.Layers.ItemU(connectedlayerNameU)
            Catch
            End Try

            ' clear the currently connected shapes from the connected layer
            Dim currentShape As Microsoft.Office.Interop.Visio.Shape = Nothing
            For Each kvp As KeyValuePair(Of Integer, String) In m_dictConnected
                currentShape = drawingPage.Shapes.ItemFromID(kvp.Key)
                ' clear the currentshape of all layer information (will add back selected list later)
                currentShape.CellsSRC(VisSectionIndices.visSectionObject, VisRowIndices.visRowLayerMem, VisCellIndices.visLayerMember).FormulaForceU = """"""
            Next kvp
            If Not (m_dictConnected Is Nothing) Then
                m_dictConnected = Nothing
            End If
            m_dictConnected = New Dictionary(Of Integer, String)

            Dim intX As Integer
            Dim strRck As String = "rckCompKey_"
            Dim rckTarget As Microsoft.Office.Interop.Visio.Shape = Nothing

            Dim rckSource As Microsoft.Office.Interop.Visio.Shape = Nothing
            For Each kvp As KeyValuePair(Of Integer, String) In m_dictComponents
                If LCase(kvp.Value) = LCase(strRck & CStr(rlSource.rckKey)) Then
                    rckSource = drawingPage.Shapes.ItemFromID(kvp.Key)
                    Exit For
                End If
            Next kvp
            Dim linkShape As Microsoft.Office.Interop.Visio.Shape
            For intX = 0 To rlTargets.Count - 1
                ' make sure the source and target rack keys are different
                If rlTargets.Item(intX).rckKey <> rlSource.rckKey Then
                    For Each kvp As KeyValuePair(Of Integer, String) In m_dictComponents
                        If LCase(kvp.Value) = LCase(strRck & CStr(rlTargets(intX).rckKey)) Then
                            rckTarget = drawingPage.Shapes.ItemFromID(kvp.Key)
                            Exit For
                        End If
                    Next kvp
                    If Not (rckTarget Is Nothing) Then
                        _clsVisio.addShapeToLayer(drawingPage, rckTarget, connectedlayerNameU, True)
                        linkShape = _clsVisio.ConnectWithDynamicGlueAndConnector(rckSource, rckTarget)
                        ' give it a shapedata field so we can place it in the page dictionary
                        _clsVisio.ForceShapeData(linkShape, "linkName", "", "attrNetworkLink")
                        ' clear existing layers
                        linkShape.CellsSRC(VisSectionIndices.visSectionObject, VisRowIndices.visRowLayerMem, VisCellIndices.visLayerMember).FormulaForceU = """"""
                        _clsVisio.addShapeToLayer(drawingPage, linkShape, connectedlayerNameU, False)
                    End If ' test to find if we found the target shape
                End If ' test to make sure we are not looking at the source
            Next intX

            System.Windows.Forms.Application.DoEvents()

            ' give the drawing control focus
            Me.drawingControl.Focus()
            ' select the source rack
            drawingWindow.Select(rckSource, 2)

            ' make sure the selected racks are on the correct layers
            highlightSelectedRacks()

            drawingWindow.DeselectAll()

        Catch com As COMException
            ' add com exception handler here
            '********* visio snippet vb.net vis0056vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(com, "Com+ Policy")
            If (rethrow) Then
                Throw
            End If

        Catch ex As Exception
            ' add exception handler here
            '********* visio snippet vb.net vis0059vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If

        End Try

    End Sub

    '
    ' this loads the detailed rack data into the data class and calls the draw racks form
    '
    Private Sub loadDrawData()

        Dim timeStart As DateTime = Now
        Dim timeStop As DateTime

        Me.Cursor = Cursors.WaitCursor

        Try

            ' default for loading data is to not have data recordsets
            _clsData._BlnDR = My.Settings.load_datarecordsets

            Dim colRacks As Collection(Of rackURRI) = Nothing

            ' if something is selected in the listview handle it as a composite/single
            If 0 < lvwSelectedRacks.Items.Count Then
                colRacks = New Collection(Of rackURRI)
                Dim liRackUrri As ListViewItem
                For Each liRackUrri In lvwSelectedRacks.Items
                    Dim strURRI As String = liRackUrri.Text
                    Dim csvValue As String()
                    strURRI = strURRI.Replace("[", "")
                    strURRI = strURRI.Replace("]", "")
                    csvValue = strURRI.Split({","c}, _
                            5, StringSplitOptions.None)
                    ' create a urri object 
                    Dim newUrri As rackURRI = New rackURRI
                    newUrri.clientKey = CInt(csvValue(0))
                    newUrri.locKey = CInt(csvValue(1))
                    newUrri.attrlocKey = CInt(csvValue(2))
                    newUrri.rowKey = CInt(csvValue(3))
                    newUrri.rckKey = CInt(csvValue(4))
                    colRacks.Add(newURRI)
                Next
            End If

            Dim intRackCt As Integer = 0
            If colRacks IsNot Nothing Then
                intRackCt = colRacks.Count
            End If

            If intRackCt < 1 _
                And currRowKey < 1 Then
                MsgBox("Nothing Currently Selected")
                Me.Cursor = Cursors.Default
                Exit Sub
            End If

            ' get the dgmasters table (needed for datagraphics
            sblStatusOne.Text = "Loading Data"
            sblStatusTwo.Text = "Data Graphics"


            If 0 < intRackCt Then
                ' composite row or single rack
                sblStatusTwo.Text = "Network Data"
                System.Windows.Forms.Application.DoEvents()
                _clsData.loadAttrNetwork(-1, colRacks, Nothing)
                sblStatusTwo.Text = "Port Data"
                System.Windows.Forms.Application.DoEvents()
                _clsData.loadAttrPortData(-1, colRacks, Nothing)
                sblStatusTwo.Text = "Component Data"
                System.Windows.Forms.Application.DoEvents()
                _clsData.loadComponents(-1, colRacks, Nothing)
                sblStatusTwo.Text = "Cabinet Data"
                System.Windows.Forms.Application.DoEvents()
                _clsData.loadCabinetView(-1, colRacks, Nothing)
                sblStatusTwo.Text = "Network Links"
                System.Windows.Forms.Application.DoEvents()
                _clsData.loadNetworkLinksTable(-1, colRacks, Nothing)

            Else
                ' row query
                sblStatusTwo.Text = "Network Data"
                System.Windows.Forms.Application.DoEvents()
                _clsData.loadAttrNetwork(currRowKey)
                sblStatusTwo.Text = "Port Data"
                System.Windows.Forms.Application.DoEvents()
                _clsData.loadAttrPortData(currRowKey)
                sblStatusTwo.Text = "Component Data"
                System.Windows.Forms.Application.DoEvents()
                _clsData.loadComponents(currRowKey)
                sblStatusTwo.Text = "Cabinet Data"
                System.Windows.Forms.Application.DoEvents()
                _clsData.loadCabinetView(currRowKey)
                sblStatusTwo.Text = "Network Links"
                System.Windows.Forms.Application.DoEvents()
                _clsData.loadNetworkLinksTable(-1, listRacksInRow(currRowKey))
            End If

            sblStatusOne.Text = "Load Complete"
            sblStatusTwo.Text = ""




        Catch ex As Exception
            '********* visio snippet vb.net vis0059vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try

        Me.Cursor = Cursors.Default

        timeStop = Now
        Dim timeDiff As TimeSpan = timeStop - timeStart
        Dim intHr As Integer = timeDiff.Hours
        Dim intMin As Integer = timeDiff.Minutes
        Dim intSec As Integer = timeDiff.Seconds

        Dim TimeString As String = CStr(intHr) & ":" & CStr(intMin) & ":" & CStr(intSec)
        Dim strMessage As String = "Data Load Finished" & " ( " & TimeString & " )"

        Dim dlgSummary As dlgDataSummary = New dlgDataSummary()
        dlgSummary.lblReadTime.Text = strMessage
        dlgSummary.ListDataTables(_clsData.m_ds)
        dlgSummary.ShowDialog()
        dlgSummary = Nothing




    End Sub



    '
    ' need this for row selection of cables
    '
    Private Function listRacksInRow(ByVal intRowKey As Int32) As Collection(Of rackURRI)



        Dim colReturn As Collection(Of rackURRI) = New Collection(Of rackURRI)


        Try
            Dim rackQuery = From cabinets In _clsData.m_ds.Tables(DC_RackTables.tblAttrCabinet.ToString).AsEnumerable() _
                Where cabinets!rckrowKey = intRowKey _
                Select cabinets _
                Order By cabinets!rckRowPos

            If 0 < rackQuery.Count Then
                For Each rck In rackQuery
                    Dim newURRI As clsDC_RackData.rackURRI = New clsDC_RackData.rackURRI
                    Dim colURRI As Collection = New Collection
                    newURRI.clientKey = currClientKey
                    newURRI.locKey = currLocKey
                    newURRI.attrlocKey = currSubLocKey
                    newURRI.rowKey = intRowKey
                    newURRI.rckKey = rck.Item("rckCompKey")
                    colReturn.Add(newURRI)
                Next rck
            End If

        Catch ex As Exception
            '********* visio snippet vb.net vis0059vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try

        Return colReturn

    End Function



    '
    ' create a csv string with end brackets from a collection
    '
    Private Function BuildCsvString _
        (ByVal colA As Collection) _
        As String

        Dim intY As Integer
        Dim strCsv As String = "[]"
        Try

            If (colA Is Nothing) _
                Or (colA.Count = 0) Then
                Exit Try
            Else
                With colA
                    ' start bracket
                    strCsv = "["
                    For intY = 1 To colA.Count
                        strCsv = strCsv & CStr(colA.Item(intY))
                        If intY <> colA.Count Then
                            strCsv = strCsv & ","
                        End If ' test for last position
                    Next intY
                    ' end bracket
                    strCsv = strCsv & "]"
                End With
            End If

        Catch ex As Exception
            '********* visio snippet vb.net visXXXX ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
            strCsv = "[]"
        End Try

        BuildCsvString = strCsv

    End Function


#End Region

#Region " Form Events "

    '
    '
    '
    Private Sub frmLocationData_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing


        Try


            _clsVisio = Nothing
            _clsData = Nothing
            _clsReports = Nothing

            NullAndRelease(mappingMap)
            NullAndRelease(drawingPage)

            If Not (drawingDocument Is Nothing) Then
                drawingDocument.Saved = True
                _drawingDocument = Nothing
                CType(_drawingApplication, Microsoft.Office.Interop.Visio.Application).Quit()
                _drawingApplication = Nothing
            End If

            If Not (mappingMap Is Nothing) Then
                mappingApplication.ActiveMap.Saved = True  ' Forestall the "Save Changes?" dialog
                _mappingMap = Nothing
                CType(_mappingApplication, MapPoint.Application).Quit() ' Cast to base type.
                _mappingApplication = Nothing
            End If

            System.GC.Collect()
            System.GC.Collect()



        Catch com As COMException
            '********* visio snippet vb.net vis0056vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(com, "Com+ Policy")
            If (rethrow) Then
                Throw
            End If

        Catch ex As Exception
            ' add exception handler here
            '********* visio snippet vb.net vis0059vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If

        End Try

    End Sub

    '
    '********* visio snippet vb.net vis0098vb ******************
    Private Sub NullAndRelease(ByVal runtimeObject As Object)

        Try

            If Not (runtimeObject Is Nothing) Then

                ' The RCW's reference count gets incremented each time the
                ' COM pointer is passed from unmanaged to managed code.
                ' Call ReleaseComObject in a loop until it returns 0 to be
                ' sure that the underlying COM object gets released.
                Dim i As Integer
                Do
                    i = System.Runtime.InteropServices.Marshal. _
                        ReleaseComObject(runtimeObject)
                Loop While i > 0
            End If
        Finally
            runtimeObject = Nothing
        End Try
    End Sub

    '
    '
    '
    Private Sub frmLocationData_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load


        Try

            initMapControl()

        Catch com As COMException
            '********* visio snippet vb.net vis0056vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(com, "Com+ Policy")
            If (rethrow) Then
                Throw
            End If

        Catch ex As Exception
            ' add exception handler here
            '********* visio snippet vb.net vis0059vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If

        End Try


    End Sub

    '
    '
    '
    Private Sub LoadToolStripMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles LoadToolStripMenuItem.Click
        openVisioDocumentDialog()
    End Sub

    '
    '
    '
    Private Sub SaveToolStripMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles SaveToolStripMenuItem.Click
        saveVisioDocumentDialog()
    End Sub

    '
    '
    '
    Private Sub ExitToolStripMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click


        Try



            If Not (drawingDocument Is Nothing) Then
                drawingDocument.Saved = True
                drawingDocument.Close()
                _drawingDocument = Nothing
                CType(_drawingApplication, Microsoft.Office.Interop.Visio.Application).Quit()
                _drawingApplication = Nothing
            End If

        Catch com As COMException
            '********* visio snippet vb.net vis0056vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(com, "Com+ Policy")
            If (rethrow) Then
                Throw
            End If

        Catch ex As Exception
            ' add exception handler here
            '********* visio snippet vb.net vis0059vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If

        End Try


        Try

            If Not (mappingMap Is Nothing) Then
                mappingApplication.ActiveMap.Saved = True  ' Forestall the "Save Changes?" dialog
                _mappingMap = Nothing
                CType(_mappingApplication, MapPoint.Application).Quit() ' Cast to base type.
                _mappingApplication = Nothing
            End If

        Catch com As COMException
            '********* visio snippet vb.net vis0056vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(com, "Com+ Policy")
            If (rethrow) Then
                Throw
            End If

        Catch ex As Exception
            ' add exception handler here
            '********* visio snippet vb.net vis0059vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If

        End Try


        Me.Close()

    End Sub


    '
    ' turn grid on and off
    '
    Private Sub GridToolStripMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles GridToolStripMenuItem.Click
        If GridToolStripMenuItem.Checked = True Then
            GridToolStripMenuItem.Checked = False
        Else
            GridToolStripMenuItem.Checked = True
        End If

        drawingWindow.ShowGrid = GridToolStripMenuItem.Checked

    End Sub

    '
    ' open/close the panzoom window 
    '
    Private Sub PanZoomToolStripMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles PanZoomToolStripMenuItem.Click
        Dim visWindow As Microsoft.Office.Interop.Visio.Window = Nothing
        Try
            visWindow = drawingWindow.Windows.ItemFromID( _
                Microsoft.Office.Interop.Visio.VisWinTypes. _
                visWinIDPanZoom)
        Catch
        End Try

        If visWindow IsNot Nothing Then
            If visWindow.Visible = False Then
                visWindow.Visible = True
            Else
                visWindow.Visible = False
            End If
        End If

    End Sub

    '
    ' demo creating a single wan topology in both mappoint and visio maps
    '
    Private Sub DemoMultiSiteToolStripMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles DemoMultiSiteToolStripMenuItem.Click
        demoAddWanToMappoint()
    End Sub

    '
    ' copy the current mappoint map to the active page
    '
    Private Sub CopyMappointToolStripMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles CopyMappointToolStripMenuItem.Click
        ImportMap()
    End Sub

    '
    ' show connected racks based on the selected rack in the treeview control
    '
    Private Sub ConnectedRacksToolStripMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ConnectedRacksToolStripMenuItem.Click

        Try

            ' keep this as a database operation because of the amount of data involved
            If blnExternalSource = True Then Exit Sub

            ' delete any links that may be on the page
            Dim shpLink As Microsoft.Office.Interop.Visio.Shape = Nothing
            For Each kvp As KeyValuePair(Of Integer, String) In m_dictLinks
                shpLink = drawingPage.Shapes.ItemFromID(kvp.Key)
                shpLink.Delete()
            Next kvp

            ' get the urri
            If 0 < LastUrri.rckKey Then
                Dim colConnected As Collection(Of clsDC_RackData.rackURRI) = New Collection(Of clsDC_RackData.rackURRI)
                colConnected = getConnectedRackList(LastUrri.rckKey)
                showConnectedRackList(LastUrri, colConnected)
            Else
                MsgBox("Last selected treenode/rack URRI not valid for connections")
            End If



            initPageDictionaries(drawingPage)

        Catch com As COMException
            ' add com exception handler here
            '********* visio snippet vb.net vis0056vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(com, "Com+ Policy")
            If (rethrow) Then
                Throw
            End If

        Catch ex As Exception
            ' add exception handler here
            '********* visio snippet vb.net vis0059vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If

        End Try
    End Sub

    '
    ' remove selected item from selected racks listview
    '
    Private Sub lvwSelectedRacks_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lvwSelectedRacks.Click
        Try


            Dim liRackUrri As ListViewItem = lvwSelectedRacks.SelectedItems(0)
            Dim visShape As Microsoft.Office.Interop.Visio.Shape
            Dim strURRI As String = liRackUrri.Text

            Dim csvValue As String()
            strURRI = strURRI.Replace("[", "")
            strURRI = strURRI.Replace("]", "")
            csvValue = strURRI.Split({","c}, _
                    5, StringSplitOptions.None)

            For Each kvp As KeyValuePair(Of Integer, String) In m_dictComponents
                If LCase(kvp.Value) = LCase("rckCompKey_" & CStr(csvValue(4))) Then
                    visShape = drawingPage.Shapes.ItemFromID(kvp.Key)
                    visShape.CellsSRC(VisSectionIndices.visSectionObject, VisRowIndices.visRowLayerMem, VisCellIndices.visLayerMember).FormulaForceU = """"""
                    _clsVisio.RemoveShapeFromLayer(drawingPage, visShape, selectedLayerNameU, True)
                    Exit For
                End If
            Next kvp

            ' reset the lasturri
            ' create a blank urri object 
            Dim newUrri As rackURRI = New rackURRI
            newURRI.clientKey = -1
            newURRI.locKey = -1
            newURRI.attrlocKey = -1
            newURRI.rowKey = -1
            newURRI.rckKey = -1
            LastUrri = newURRI


            ' if this is the only one then get out
            If lvwSelectedRacks.Items.Count = 1 Then
                lvwSelectedRacks.Items.Clear()
                Exit Sub
            End If

            lvwSelectedRacks.Items.Remove(lvwSelectedRacks.SelectedItems(0))

            System.Windows.Forms.Application.DoEvents()


        Catch ex As Exception
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try
    End Sub

    '
    ' get the list of racks in the selected listview and move them to the selected racks layer
    '
    Private Sub highlightSelectedRacks()


        Try

            Dim liRackUrri As ListViewItem = Nothing
            Dim colRackItems As System.Windows.Forms.ListView.ListViewItemCollection
            colRackItems = lvwSelectedRacks.Items

            Dim visShape As Microsoft.Office.Interop.Visio.Shape
            Dim csvValue As String()
            For Each liRackUrri In colRackItems
                Dim strURRI As String = liRackUrri.Text
                strURRI = strURRI.Replace("[", "")
                strURRI = strURRI.Replace("]", "")
                csvValue = strURRI.Split({","c}, _
                        5, StringSplitOptions.None)

                For Each kvp As KeyValuePair(Of Integer, String) In m_dictComponents
                    If LCase(kvp.Value) = LCase("rckCompKey_" & CStr(csvValue(4))) Then
                        visShape = drawingPage.Shapes.ItemFromID(kvp.Key)
                        visShape.CellsSRC(VisSectionIndices.visSectionObject, VisRowIndices.visRowLayerMem, VisCellIndices.visLayerMember).FormulaForceU = """"""
                        _clsVisio.addShapeToLayer(drawingPage, visShape, selectedLayerNameU, True)
                        Exit For
                    End If
                Next kvp
            Next liRackUrri



        Catch com As COMException
            ' add com exception handler here
            '********* visio snippet vb.net vis0056vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(com, "Com+ Policy")
            If (rethrow) Then
                Throw
            End If

        Catch ex As Exception
            ' add exception handler here
            '********* visio snippet vb.net vis0059vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If

        End Try

    End Sub

    '
    ' based on the length of the current path selected in the treeview control
    ' pull up a report in the report viewer control
    '
    Private Sub CreateReportToolStripMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles CreateReportToolStripMenuItem.Click
        '
        ' make a dataset/datatable out of the structured array
        '
        Try
            Dim strText As String = ""
            Try
                strText = tvLocation.SelectedNode.Text
            Catch
            End Try

            If strText = "" Then
                MsgBox("Couldn't find selected node in treeview")
                Exit Sub
            End If

            Dim returnValue As String()

            Dim strFullPath As String = tvLocation.SelectedNode.FullPath
            Dim strNodeName As String = ""

            ' parse out the fullpath
            returnValue = strFullPath.Split({"\"c}, _
                    5, StringSplitOptions.None)


            ' default to client record

            Dim intReport As clsDC_RackReporting.baseReports = clsDC_RackReporting.baseReports.rptClientsAll
            Dim dtReport As System.Data.DataTable = Nothing


            Select Case returnValue.Count
                Case 1
                    intReport = clsDC_RackReporting.baseReports.rptClientsAll
                    dtReport = _clsData.m_ds.Tables(DC_RackTables.tblClient.ToString)
                Case 2
                    intReport = clsDC_RackReporting.baseReports.rptLocationsAll
                    dtReport = _clsData.m_ds.Tables(DC_RackTables.tblLocation.ToString)
                Case 3
                    intReport = clsDC_RackReporting.baseReports.rptAttrLocationsAll
                    dtReport = _clsData.m_ds.Tables(DC_RackTables.tblAttrLocation.ToString)
                Case 4
                    intReport = clsDC_RackReporting.baseReports.rptCabinetRowsAll
                    dtReport = _clsData.m_ds.Tables(DC_RackTables.tblAttrCabinetRow.ToString)
                Case 5
                    intReport = clsDC_RackReporting.baseReports.rptAttrCabinetsAll
                    dtReport = _clsData.m_ds.Tables(DC_RackTables.tblAttrCabinet.ToString)
                Case Else
                    Exit Sub
            End Select



            Dim frmExport As frmReportViewer = New frmReportViewer(intReport, dtReport)
            frmExport.ShowDialog()
            frmExport.Dispose()
            frmExport = Nothing


        Catch com As COMException
            ' add com exception handler here
            '********* visio snippet vb.net vis0056vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(com, "Com+ Policy")
            If (rethrow) Then
                Throw
            End If
        Catch err As Exception
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(err, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try


    End Sub


    '
    '
    '
    Private Sub AboutToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AboutToolStripMenuItem.Click

        Dim frmAbout As frmAboutBox = New frmAboutBox
        frmAbout.ShowDialog()
        frmAbout.Dispose()
        frmAbout = Nothing

    End Sub


#End Region

#Region " External get/save "


    '
    ' to link the tables internally, this helps us to do master/detail types of data display
    '
    Private Sub buildTableRelationships()

        Try
            ' relationship between client and location table
            _clsData.m_ds.Relations.Add _
                ("ClientLocations", _
                _clsData.m_ds.Tables(DC_RackTables.tblClient.ToString).Columns("clientKey"), _
                _clsData.m_ds.Tables(DC_RackTables.tblLocation.ToString).Columns("locClientKey"))
            ' relation between location and attrLocation
            _clsData.m_ds.Relations.Add _
                ("SubLocations", _
                 _clsData.m_ds.Tables(DC_RackTables.tblLocation.ToString).Columns("locKey"), _
                 _clsData.m_ds.Tables(DC_RackTables.tblAttrLocation.ToString).Columns("attrlocSiteKey"))
            ' relation between attrLocation and cabinet rows
            _clsData.m_ds.Relations.Add _
                ("LocationRows", _
                 _clsData.m_ds.Tables(DC_RackTables.tblAttrLocation.ToString).Columns("attrlocKey"), _
                 _clsData.m_ds.Tables(DC_RackTables.tblAttrCabinetRow.ToString).Columns("rowLoc"))
            'relation between cabinet rows and cabinets
            _clsData.m_ds.Relations.Add _
                ("RowCabinets", _
                _clsData.m_ds.Tables(DC_RackTables.tblAttrCabinetRow.ToString).Columns("rowKey"), _
                _clsData.m_ds.Tables(DC_RackTables.tblAttrCabinet.ToString).Columns("rckRowKey"))

            '_clsData.m_ds.Relations.Add _
            '    ("LocationGeo", _
            '     _clsData.m_ds.Tables(DC_RackTables.tblLocation.ToString).Columns("locKey"), _
            '     _clsData.m_ds.Tables(DC_RackTables.tblAttrGeoData.ToString).Columns("geoSiteKey"))

            '_clsData.m_ds.Relations.Add _
            '    ("SubLocationGeo", _
            '     _clsData.m_ds.Tables(DC_RackTables.tblAttrLocation.ToString).Columns("attrlocKey"), _
            '     _clsData.m_ds.Tables(DC_RackTables.tblAttrGeoData.ToString).Columns("geoLocKey"))


        Catch sql As SqlException
            '********* visio snippet vb.net vis0057vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(sql, "Database Policy")
            If (rethrow) Then
                Throw
            End If

        Catch ex As Exception
            ' add exception handler here
            '********* visio snippet vb.net vis0059vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If

        End Try



    End Sub

    '
    ' load data from database
    '
    Private Sub loadTestLocationData()

        Try

            ' default get all the data for ease of demo
            ' client/root data
            _clsData.loadClients()
            '
            _clsData.loadLocationTable()
            ' 
            _clsData.loadSubLocationTable()
            ' 
            Dim clsCabRows As clsAttrCabinetRows = New clsAttrCabinetRows
            clsCabRows.dbSelectAllCabinetRows()
            _clsData.loadCabrowsTable(-1, clsCabRows.m_ds.Tables(DC_RackTables.tblAttrCabinetRow.ToString))
            clsCabRows = Nothing

            Dim clsCab As clsAttrCabinet = New clsAttrCabinet
            clsCab.dbSelectAllCabinets()
            _clsData.loadCabinets(-1, Nothing, clsCab.m_ds.Tables(DC_RackTables.tblAttrCabinet.ToString))
            clsCab = Nothing

            _clsData.loadGeoDataTable()

            buildTableRelationships()


        Catch com As COMException
            ' add com exception handler here
            '********* visio snippet vb.net vis0056vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(com, "Com+ Policy")
            If (rethrow) Then
                Throw
            End If

        Catch sql As SqlException
            '********* visio snippet vb.net vis0057vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(sql, "Database Policy")
            If (rethrow) Then
                Throw
            End If

        Catch ex As Exception
            ' add exception handler here
            '********* visio snippet vb.net vis0059vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If

        End Try


    End Sub




    ' dictTables is a list of the tables we will use in this solution
    ' enumTable value and the exported table name
    Private dictTables As Dictionary(Of Int16, String)

    '
    ' used to load test case data from excel source
    '
    Private Sub loadExcelTestData()

        Try

            Me.sblStatusOne.Text = "Initializing"

            Dim dtTemp As System.Data.DataTable = Nothing
            Dim dictTemp As Dictionary(Of Int16, String) = New Dictionary(Of Int16, String)

            ' read the worksheet list into a local dictionary
            dictTemp = readExcelWorksheetList(My.Settings.path_custom_data & My.Settings.workbook_custom_data)
            Dim blnContains As Boolean = True
            ' are there enough worksheets
            If dictTables.Count <= dictTemp.Count Then
                For Each kvp In dictTables
                    If dictTemp.ContainsValue(kvp.Value) = False Then
                        blnContains = False
                    End If
                Next kvp
            Else
                MsgBox("Not enough worksheets for this solutions")
                Exit Sub
            End If

            If blnContains = False Then
                MsgBox("Could not find all necessary worksheets")
                Exit Sub
            End If

            ' now read the worksheets into the tables
            ' the keyvalue pairs are the table index, and the modified table name
            For Each kvp In dictTables
                dtTemp = Nothing
                dtTemp = readExcelWorksheet(My.Settings.path_custom_data & My.Settings.workbook_custom_data, kvp.Value)
                If dtTemp Is Nothing Then GoTo NextKvp
                dtTemp.TableName = CType(kvp.Key, DC_RackTables).ToString

                Select Case kvp.Key
                    Case DC_RackTables.tblClient
                        Me.sblStatusTwo.Text = DC_RackTables.tblClient.ToString & " loading "
                        _clsData.loadClients(dtTemp)
                    Case DC_RackTables.tblLocation
                        Me.sblStatusTwo.Text = DC_RackTables.tblLocation.ToString & " loading "
                        _clsData.loadLocationTable(dtTemp)
                    Case DC_RackTables.tblAttrLocation
                        Me.sblStatusTwo.Text = DC_RackTables.tblAttrLocation.ToString & " loading "
                        _clsData.loadSubLocationTable(-1, dtTemp)
                    Case DC_RackTables.tblAttrCabinetRow
                        Me.sblStatusTwo.Text = DC_RackTables.tblAttrCabinetRow.ToString & " loading "
                        _clsData.loadCabrowsTable(-1, dtTemp)
                    Case DC_RackTables.tblAttrCabinet
                        Me.sblStatusTwo.Text = DC_RackTables.tblAttrCabinet.ToString & " loading "
                        _clsData.loadCabinets(-1, Nothing, dtTemp)
                    Case DC_RackTables.tblAttrGeoData
                        Me.sblStatusTwo.Text = DC_RackTables.tblAttrGeoData.ToString & " loading "
                        _clsData.loadGeoDataTable(dtTemp)
                End Select
NextKvp:
            Next kvp

            buildTableRelationships()

            Me.sblStatusOne.Text = "DataLoaded"
            Me.sblStatusTwo.Text = _clsData.m_ds.Tables.Count.ToString & " tables loaded"

        Catch ex As Exception
            '********* visio snippet vb.net vis0059vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try

    End Sub

    '
    ' create the list of tables that we will need for this visio report
    ' these are the tables that have something to do with where we are
    '
    Private Sub loadTestDictTables()


        dictTables = Nothing
        dictTables = New Dictionary(Of Int16, String)

        dictTables.Add(DC_RackTables.tblClient, "dbo_tblClient")
        dictTables.Add(DC_RackTables.tblLocation, "dbo_tblLocation")
        dictTables.Add(DC_RackTables.tblAttrLocation, "dbo_tblAttrLocation")
        dictTables.Add(DC_RackTables.tblAttrCabinetRow, "dbo_tblAttrCabinetRow")
        dictTables.Add(DC_RackTables.tblAttrCabinet, "dbo_tblAttrCabinet")
        dictTables.Add(DC_RackTables.tblAttrGeoData, "dbo_tblAttrGeoData")


    End Sub

    '
    ' Reads a workbook and returns a collection of worksheet names as a 
    ' dictionary
    '
    Private Function readExcelWorksheetList _
        (ByVal strWorkbook As String) _
        As Dictionary(Of Int16, String)

        Dim dictReturn As Dictionary(Of Int16, String) = New Dictionary(Of Int16, String)
        Dim objExcel As Microsoft.Office.Interop.Excel.Application = Nothing
        Dim objWorkBook As Microsoft.Office.Interop.Excel.Workbook = Nothing
        Dim objWorkSheets As Microsoft.Office.Interop.Excel.Worksheet = Nothing

        Try

            If (strWorkbook Is Nothing) Then
                Throw New System.ArgumentNullException("strWorkbookValueIsNull", _
                    "Workbook is Null.")
                GoTo ExitFunction
            End If

            If File.Exists(strWorkbook) = False Then
                MsgBox("Workbook (" & strWorkbook & ") not found")
                GoTo ExitFunction
            End If

            Dim ExcelSheetName As String = ""
            objExcel = CreateObject("Excel.Application")
            objWorkBook = objExcel.Workbooks.Open(strWorkbook)
            Dim intX As Integer = 1
            For Each objWorkSheets In objWorkBook.Worksheets
                dictReturn.Add(intX, objWorkSheets.Name)
                intX = intX + 1
            Next

ExitFunction:

        Catch com As COMException
            '********* visio snippet vb.net vis0056vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(com, "Com+ Policy")
            If (rethrow) Then
                Throw
            End If

        Catch ex As Exception
            '********* visio snippet vb.net vis0059vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If

        Finally

            objWorkSheets = Nothing
            objWorkBook = Nothing
            objExcel.Quit()
            objExcel = Nothing

        End Try

        Return dictReturn

    End Function

    '
    ' read a worksheet and return a datatable
    '
    Private Function readExcelWorksheet _
            (ByVal strWorkBook As String, _
            ByVal strWorkSheet As String) _
            As System.Data.DataTable


        Dim dtReturn As System.Data.DataTable = Nothing

        Try

            If (strWorkBook Is Nothing) _
                Or strWorkBook = "" Then
                Throw New System.ArgumentNullException("strWorkbookValueIsNull", _
                    "Workbook is Null.")
                GoTo ExitFunction
            End If

            If File.Exists(strWorkBook) = False Then
                MsgBox("Workbook (" & strWorkBook & ") not found")
                GoTo ExitFunction
            End If

            Dim DS As System.Data.DataSet
            Dim MyCommand As OleDb.OleDbDataAdapter
            Dim MyConnection As OleDb.OleDbConnection
            Dim strConnection As String = "Provider=Microsoft.ACE.OLEDB.12.0;" _
                                          & "Data Source=" & strWorkBook & ";" _
                                          & "Extended Properties=" & """Excel 12.0 Xml;HDR=YES""" & ";"
            MyConnection = New OleDb.OleDbConnection(strConnection)
            MyCommand = New OleDb.OleDbDataAdapter( _
                         "select * from [" & strWorkSheet & "$]", MyConnection)
            DS = New System.Data.DataSet()
            MyCommand.Fill(DS)
            dtReturn = DS.Tables(0)
            dtReturn.TableName = strWorkSheet
            MyConnection.Close()

ExitFunction:

        Catch oledb As OleDbException
            '********* visio snippet vb.net visXXXX ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(oledb, "Database Policy")
            If (rethrow) Then
                Throw
            End If
        Catch ex As Exception
            '********* visio snippet vb.net visXXXX ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try

        Return dtReturn

    End Function

    '
    ' 
    '
    Private Sub saveVisioDocumentDialog()



        Try

            Dim visDoc As Microsoft.Office.Interop.Visio.Document = Me.drawingDocument

            ' flag the document as one of ours
            Dim docsheet As Microsoft.Office.Interop.Visio.Shape = visDoc.DocumentSheet
            _clsVisio.ForceUserProperty(docsheet, "Solution", "DC_Rack")
            _clsVisio.ForceUserProperty(docsheet, "Diagram", defaultDocumentName)

            SaveFileDialog.Filter = "vsd files (*.vsd)|*.vsd|All files (*.*)|*.*"
            SaveFileDialog.FilterIndex = 1
            SaveFileDialog.RestoreDirectory = True

            Dim dlgResult As DialogResult = SaveFileDialog.ShowDialog

            If dlgResult = DialogResult.OK Then
                ' if we have a recordset pointer for components ask to check on saving the data
                Dim resultMsg As MsgBoxResult = MsgBox("Save Hidden Data?", MsgBoxStyle.YesNo, "SaveHiddenData")
                If resultMsg = MsgBoxResult.No Then
                    ' get rid of recordsets, masters, and personal information
                    visDoc.RemoveHiddenInformation(Microsoft.Office.Interop.Visio.VisRemoveHiddenInfoItems.visRHIDataRecordsets + _
                                                   Microsoft.Office.Interop.Visio.VisRemoveHiddenInfoItems.visRHIMasters + _
                                                   Microsoft.Office.Interop.Visio.VisRemoveHiddenInfoItems.visRHIPersonalInfo)
                End If

                visDoc.SaveAsEx(SaveFileDialog.FileName, Microsoft.Office.Interop.Visio.tagVisOpenSaveArgs.visSaveAsWS + _
                                Microsoft.Office.Interop.Visio.tagVisOpenSaveArgs.visSaveAsListInMRU)

            Else

                MsgBox("Save Cancelled")

            End If

        Catch com As COMException
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(com, "Com+ Policy")
            If (rethrow) Then
                Throw
            End If
        Catch err As Exception
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(err, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try


        System.GC.Collect()

    End Sub

    '
    '
    '
    Private Sub openVisioDocumentDialog()



        Try

            OpenFileDialog.InitialDirectory = "c:\"
            OpenFileDialog.FileName = "*.vsd"
            OpenFileDialog.Filter = "visio drawings (*.vsd)|*.vsd|All files (*.*)|*.*"
            OpenFileDialog.FilterIndex = 1
            OpenFileDialog.RestoreDirectory = True

            Dim strPath As String = ""
            Dim dlgResult As System.Windows.Forms.DialogResult = OpenFileDialog.ShowDialog

            If dlgResult = System.Windows.Forms.DialogResult.OK Then

                Me.drawingControl.Src = OpenFileDialog.FileName

                Me.drawingWindow = Me.drawingControl.Window
                Me.drawingApplication = Me.drawingControl.Window.Application
                Me.drawingDocument = Me.drawingApplication.ActiveDocument
                Me.drawingPage = Me.drawingApplication.ActivePage

                ' flag it as already having been saved
                Me.drawingDocument.Saved = True

            End If

        Catch com As COMException
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(com, "Com+ Policy")
            If (rethrow) Then
                Throw
            End If
        Catch err As Exception
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(err, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try

    End Sub

#End Region

#Region " Treeview control methods and events "


    Public Structure nodeName
        Public nodeKey As String
        Public nodeValue As Int32
    End Structure


    '
    ' urri = my.uniform rack record identifier
    ' although we really only need the rack keys for selection, we build the hierarchy for 
    ' other reasons
    '
    Private Function buildTreeURRI(ByVal nodeLocation As TreeNode) As rackURRI


        Dim urriReturn As rackURRI = New rackURRI
        ' init the structure
        urriReturn.clientKey = -1
        urriReturn.locKey = -1
        urriReturn.attrlocKey = -1
        urriReturn.rowKey = -1
        urriReturn.rckKey = -1

        Try


            Dim strText As String = ""
            Dim ndeTemp As TreeNode = Nothing

            Dim returnValue As String()

            Dim strFullPath As String = ""
            Dim strNodeName As String = ""


            Dim ndeTempName As nodeName = New nodeName
            returnValue = nodeLocation.Name.Split({"_"c}, _
                    2, StringSplitOptions.None)

            ndeTempName.nodeKey = returnValue(0)
            ndeTempName.nodeValue = CInt(returnValue(1))

            Select Case ndeTempName.nodeKey
                Case "clientKey"
                    urriReturn.clientKey = CInt(ndeTempName.nodeValue)
                Case "locKey"
                    urriReturn.locKey = CInt(ndeTempName.nodeValue)
                Case "attrlocKey"
                    urriReturn.attrlocKey = CInt(ndeTempName.nodeValue)
                Case "rowKey"
                    urriReturn.rowKey = CInt(ndeTempName.nodeValue)
                Case "rckKey"
                    urriReturn.rckKey = CInt(ndeTempName.nodeValue)
            End Select


            ndeTemp = nodeLocation.Parent

            While (ndeTemp IsNot Nothing)
                ndeTempName = New nodeName
                returnValue = ndeTemp.Name.Split({"_"c}, _
                        2, StringSplitOptions.None)
                ndeTempName.nodeKey = returnValue(0)
                ndeTempName.nodeValue = CInt(returnValue(1))
                Select Case ndeTempName.nodeKey
                    Case "clientKey"
                        urriReturn.clientKey = CInt(ndeTempName.nodeValue)
                    Case "locKey"
                        urriReturn.locKey = CInt(ndeTempName.nodeValue)
                    Case "attrlocKey"
                        urriReturn.attrlocKey = CInt(ndeTempName.nodeValue)
                    Case "rowKey"
                        urriReturn.rowKey = CInt(ndeTempName.nodeValue)
                    Case "rckKey"
                        urriReturn.rckKey = CInt(ndeTempName.nodeValue)
                End Select
                If ndeTemp.Parent IsNot Nothing Then
                    If (ndeTemp.Parent.GetType() Is GetType(TreeNode)) Then
                        ndeTemp = ndeTemp.Parent
                    End If
                Else
                    ndeTemp = Nothing
                End If
            End While


        Catch ex As Exception
            ' add exception handler here
            '********* visio snippet vb.net vis0059vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If

        End Try

        Return urriReturn

    End Function

    '
    ' handle a treenode being selected
    '
    Private Sub tvLocation_AfterSelect(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles tvLocation.AfterSelect


        Try

            ' get a urri
            Dim newUrri As rackURRI = New rackURRI
            newUrri = buildTreeURRI(tvLocation.SelectedNode)
            ' save it
            LastUrri = newUrri

            Dim returnValue As String()
            Dim strFullPath As String = tvLocation.SelectedNode.FullPath
            Dim strNodeName As String = ""


            ' parse out the fullpath
            returnValue = strFullPath.Split({"\"c}, _
                    5, StringSplitOptions.None)

            If 2 < returnValue.Count Then
                drawingWindow.ShowGrid = True
                Me.GridToolStripMenuItem.Checked = True
            Else
                drawingWindow.ShowGrid = False
                Me.GridToolStripMenuItem.Checked = False
                currSubLocKey = -1
            End If

            ' if we have a location or sublocation change then clear the drawing page
            If newUrri.attrlocKey <> currSubLocKey _
                Or newUrri.locKey <> currLocKey Then
                ' move to the correct page
                Dim strPageName As String = defaultPageName
                drawingWindow.Page = strPageName
                drawingPage = drawingDocument.Pages(strPageName)

                Dim visSelection As Microsoft.Office.Interop.Visio.Selection = Nothing
                Dim intShapes As Integer = drawingPage.Shapes.Count
                If 0 < intShapes Then
                    drawingApplication.ActiveWindow.SelectAll()
                    visSelection = drawingWindow.Selection
                    visSelection.Delete()
                End If
            End If

            ' parse out the treenode name
            ' first string is the record field name
            ' second string is the record key
            strNodeName = tvLocation.SelectedNode.Name

            ' parse out the node name
            returnValue = strNodeName.Split({"_"c}, _
                    2, StringSplitOptions.None)

            Dim strKeyName As String = returnValue(0)
            Dim intKeyValue As Int32 = CInt(returnValue(1))

            Select Case strKeyName
                Case "clientKey"
                    currLocKey = newUrri.locKey
                    currSubLocKey = newUrri.attrlocKey
                    Exit Select
                Case "locKey"
                    syncMapControlToLocation(intKeyValue)
                    currLocKey = newUrri.locKey
                    currSubLocKey = newUrri.attrlocKey
                    Exit Select
                Case "attrlocKey"
                    syncMapControlToLocation(newUrri.locKey)
                    drawRows(newUrri)
                    Exit Select

                Case "rowKey"
                    syncMapControlToLocation(newUrri.locKey)
                    drawRows(newUrri)
                    ' might want to query the users first, in case they have
                    ' already selected multiple racks
                    Me.lvwSelectedRacks.Items.Clear()

                    Dim strKey As String = "rowKey_" & CStr(newUrri.rowKey)
                    currRowKey = newUrri.rowKey
                    Dim visShape As Microsoft.Office.Interop.Visio.Shape = Nothing
                    Try
                        visShape = drawingPage.Shapes(strKey)
                    Catch
                    End Try

                    If visShape IsNot Nothing Then
                        searchZoomObject(visShape)
                    Else
                        MsgBox("row not on page")
                    End If


                    Exit Select
                Case "rckKey"
                    syncMapControlToLocation(newUrri.locKey)
                    drawRows(newUrri)

                    Dim strKey As String = "rckCompKey_" & CStr(newUrri.rckKey)
                    Dim intKey As Int32 = -1
                    Dim visShape As Microsoft.Office.Interop.Visio.Shape = Nothing
                    Try
                        If dictComponents.ContainsValue(strKey) = True Then
                            For Each kvp As KeyValuePair(Of Int32, String) In dictComponents
                                If kvp.Value = strKey Then
                                    intKey = kvp.Key
                                    Exit For
                                End If
                            Next kvp
                            visShape = drawingPage.Shapes.ItemFromID(intKey)
                        End If
                    Catch
                    End Try

                    If visShape IsNot Nothing Then
                        searchZoomObject(visShape)
                        addUrriToListView(newUrri, Me.lvwSelectedRacks)
                        highlightSelectedRacks()

                    Else
                        MsgBox("rack not on page")
                    End If

            End Select


        Catch com As COMException
            ' add com exception handler here
            '********* visio snippet vb.net vis0056vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(com, "Com+ Policy")
            If (rethrow) Then
                Throw
            End If

        Catch ex As Exception
            ' add exception handler here
            '********* visio snippet vb.net vis0059vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If

        End Try


    End Sub
    '
    ' based on the datasets in the datacache, build the treeview control
    '
    Private Sub drawTreeview()

        Dim strKey As String = ""

        Try


            With tvLocation

                .BeginUpdate()

                .Nodes.Clear()

                ' get the client records
                For Each pRow As System.Data.DataRow In _clsData.m_ds.Tables(DC_RackTables.tblClient.ToString).Rows
                    Dim pNode As New TreeNode(pRow("clientName").ToString)
                    pNode.Name = "clientKey_" & pRow("clientKey").ToString
                    .Nodes.Add(pNode)

                    ' get the location records
                    For Each lRow As System.Data.DataRow In pRow.GetChildRows("ClientLocations")
                        Dim lNode As New TreeNode(lRow("locSiteID").ToString)
                        lNode.Name = "locKey_" & lRow("locKey").ToString
                        pNode.Nodes.Add(lNode)

                        ' sublocation records
                        For Each sRow As System.Data.DataRow In lRow.GetChildRows("SubLocations")
                            Dim sNode As New TreeNode(sRow("attrlocName").ToString)
                            sNode.Name = "attrlocKey_" & sRow("attrlocKey").ToString
                            lNode.Nodes.Add(sNode)

                            ' cabinetrow records
                            For Each cRow As System.Data.DataRow In sRow.GetChildRows("LocationRows")
                                Dim cNode As New TreeNode(cRow("rowId").ToString)
                                cNode.Name = "rowKey_" & cRow("rowKey").ToString
                                sNode.Nodes.Add(cNode)

                                ' cabinet records
                                For Each rRow As System.Data.DataRow In cRow.GetChildRows("RowCabinets")
                                    Dim rNode As New TreeNode(rRow("rckGrid").ToString)
                                    rNode.Name = "rckKey_" & rRow("rckCompKey").ToString
                                    cNode.Nodes.Add(rNode)

                                Next rRow
                            Next cRow
                        Next sRow
                    Next lRow
                Next pRow

                .EndUpdate()

            End With

        Catch com As COMException
            ' add com exception handler here
            '********* visio snippet vb.net vis0056vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(com, "Com+ Policy")
            If (rethrow) Then
                Throw
            End If

        Catch sql As SqlException
            '********* visio snippet vb.net vis0057vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(sql, "Database Policy")
            If (rethrow) Then
                Throw
            End If

        Catch ex As Exception
            ' add exception handler here
            '********* visio snippet vb.net vis0059vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If

        End Try

    End Sub
    '
    ' this is a generic so that a urri can be handled by different listview controls
    ' we can also feed it from the treeview and the visio mouse selection
    '
    Private Sub addUrriToListView _
        (ByVal rackSelected As rackURRI, _
         ByVal lvwControl As ListView, _
         Optional ByVal strCompName As String = "")
        Try

            Dim liRackUrri As ListViewItem = Nothing
            Dim colRackItems As System.Windows.Forms.ListView.ListViewItemCollection
            colRackItems = lvwSelectedRacks.Items


            Dim selecteditem As ListViewItem = Nothing

            Dim colKeyURRI As Collection = New Collection
            colKeyURRI.Add(rackSelected.clientKey)
            colKeyURRI.Add(rackSelected.locKey)
            colKeyURRI.Add(rackSelected.attrlocKey)
            colKeyURRI.Add(rackSelected.rowKey)
            colKeyURRI.Add(rackSelected.rckKey)
            Dim strKeyURRI As String = BuildCsvString(colKeyURRI)

            selecteditem = lvwControl.FindItemWithText(strKeyURRI)

            Dim itemnew As ListViewItem = Nothing
            If selecteditem Is Nothing Then
                itemnew = New ListViewItem(strKeyURRI)
                itemnew.Name = strKeyURRI
                If strCompName <> "" Then
                    itemnew.SubItems.Add(strCompName)
                End If
                itemnew.SubItems.Add(rackSelected.clientKey)
                itemnew.SubItems.Add(rackSelected.locKey)
                itemnew.SubItems.Add(rackSelected.attrlocKey)
                itemnew.SubItems.Add(rackSelected.rowKey)
                itemnew.SubItems.Add(rackSelected.rowKey)
                lvwControl.Items.Add(itemnew)
            End If

            lvwControl.Refresh()

            ' since we have a selected rack, reset the row key
            currRowKey = -1

        Catch ex As Exception
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try

    End Sub



#End Region

#Region " David Parker MapPoint(copy)/Visio(paste) "


    ' http://bvisual.spaces.live.com/blog/cns!3350D61BC93733A9!135.entry?sa=774725164
    ' used with permission
    ' converted to a function that returns the pasted image as a modified shape
    '
    Public Function ImportMap _
            (Optional ByVal strMapName As String = "map", _
             Optional ByVal dblScaleSize As Double = 1.0) _
            As Microsoft.Office.Interop.Visio.Shape


        Dim shpMap As Microsoft.Office.Interop.Visio.Shape = Nothing


        Try


            Dim left As Long = 0
            Dim top As Long = 0
            Dim width As Long = 0
            Dim height As Long = 0
            Dim altitude As Long = 0

            Dim oLocs(0 To 4) As MapPoint.Location
            Dim i As Integer = 0
            Dim x As Long = 0
            Dim y As Long = 0

            Dim distX As Double = 0
            Dim distY As Double = 0

            Dim shpBubble As Microsoft.Office.Interop.Visio.Shape = Nothing
            Dim dWidth As Double = 0
            Dim dHeight As Double = 0
            Dim dPinX As Double = 0
            Dim dPinY As Double = 0
            Dim shp As Microsoft.Office.Interop.Visio.Shape = Nothing

            mappingMap = mappingApplication.ActiveMap

            left = mappingMap.Left
            width = mappingMap.Width
            top = mappingMap.Top
            height = mappingMap.Height
            altitude = mappingMap.Altitude

            oLocs(0) = mappingMap.Location 'Centre
            x = mappingMap.LocationToX(oLocs(0))
            y = mappingMap.LocationToY(oLocs(0))

            oLocs(1) = mappingMap.XYToLocation(CLng(x - (0.5 * width)), CLng(y + (0.5 * height))) 'Bottom Left
            oLocs(2) = mappingMap.XYToLocation(CLng(x + (0.5 * width)), CLng(y + (0.5 * height))) 'Bottom Right
            oLocs(3) = mappingMap.XYToLocation(CLng(x + (0.5 * width)), CLng(y - (0.5 * height))) 'Top Right
            oLocs(4) = mappingMap.XYToLocation(CLng(x - (0.5 * width)), CLng(y - (0.5 * height))) 'Top Left

            distX = mappingMap.Distance(oLocs(1), oLocs(2))
            distY = mappingMap.Distance(oLocs(1), oLocs(4))


            mappingMap.SelectedArea.SelectArea(0, 0, 0, 0) 'width - left, height - top

            mappingMap.CopyMap()

            If shpMap Is Nothing Then
                drawingPage.Paste()
                ' get the last shape that was pasted on the page
                shpMap = drawingPage.Shapes(drawingPage.Shapes.Count)
                shpMap.Name = strMapName
                shpMap.NameU = strMapName
            End If

            shpMap.Cells("LockAspect").Formula = 1

            '
            ' make the pasted allow image smaller and add connection points (aee)
            Dim dblMapWidth As Double = shpMap.Cells("Width").ResultIU * dblScaleSize
            Dim dblMapHeight As Double = shpMap.Cells("Height").ResultIU * dblScaleSize
            shpMap.Cells("Width").Formula = dblMapWidth
            shpMap.Cells("Height").Formula = dblMapHeight
            _clsVisio.AddStandardConnections(shpMap)

            ' end my mods (aee)
            '

            Dim iRow As Integer
            If shpMap.SectionExists(VisSectionIndices.visSectionProp, VisExistsFlags.visExistsAnywhere) = 0 Then
                shpMap.AddSection(VisSectionIndices.visSectionProp)
            End If

            If shpMap.CellExistsU("Prop.MinLat", VisExistsFlags.visExistsAnywhere) = 0 Then
                iRow = shpMap.AddNamedRow(VisSectionIndices.visSectionProp, "MinLat", 0)
                shpMap.CellsSRC(VisSectionIndices.visSectionProp, iRow, VisCellIndices.visCustPropsLabel).Formula = "=""Min Latitude"""
                shpMap.CellsSRC(VisSectionIndices.visSectionProp, iRow, VisCellIndices.visCustPropsType).Formula = "=2"
            Else
                iRow = shpMap.Cells("Prop.MinLat").Row
            End If

            shpMap.CellsSRC(VisSectionIndices.visSectionProp, iRow, VisCellIndices.visCustPropsValue).Formula = "=" & oLocs(2).Latitude

            If shpMap.CellExistsU("Prop.MinLon", VisExistsFlags.visExistsAnywhere) = 0 Then
                iRow = shpMap.AddNamedRow(VisSectionIndices.visSectionProp, "MinLon", 0)
                shpMap.CellsSRC(VisSectionIndices.visSectionProp, iRow, VisCellIndices.visCustPropsLabel).Formula = "=""Min Longitude"""
                shpMap.CellsSRC(VisSectionIndices.visSectionProp, iRow, VisCellIndices.visCustPropsType).Formula = "=2"
            Else
                iRow = shpMap.Cells("Prop.MinLon").Row
            End If

            shpMap.CellsSRC(VisSectionIndices.visSectionProp, iRow, VisCellIndices.visCustPropsValue).Formula = "=" & oLocs(2).Longitude

            If shpMap.CellExistsU("Prop.MaxLat", VisExistsFlags.visExistsAnywhere) = 0 Then
                iRow = shpMap.AddNamedRow(VisSectionIndices.visSectionProp, "MaxLat", 0)
                shpMap.CellsSRC(VisSectionIndices.visSectionProp, iRow, VisCellIndices.visCustPropsLabel).Formula = "=""Max Latitude"""
                shpMap.CellsSRC(VisSectionIndices.visSectionProp, iRow, VisCellIndices.visCustPropsType).Formula = "=2"
            Else
                iRow = shpMap.Cells("Prop.MaxLat").Row
            End If

            shpMap.CellsSRC(VisSectionIndices.visSectionProp, iRow, VisCellIndices.visCustPropsValue).Formula = "=" & oLocs(4).Latitude

            If shpMap.CellExistsU("Prop.MaxLon", VisExistsFlags.visExistsAnywhere) = 0 Then
                iRow = shpMap.AddNamedRow(VisSectionIndices.visSectionProp, "MaxLon", 0)
                shpMap.CellsSRC(VisSectionIndices.visSectionProp, iRow, VisCellIndices.visCustPropsLabel).Formula = "=""Max Longitude"""
                shpMap.CellsSRC(VisSectionIndices.visSectionProp, iRow, VisCellIndices.visCustPropsType).Formula = "=2"
            Else
                iRow = shpMap.Cells("Prop.MaxLon").Row
            End If
            shpMap.CellsSRC(VisSectionIndices.visSectionProp, iRow, VisCellIndices.visCustPropsValue).Formula = "=" & oLocs(4).Longitude


            If shpMap.CellExistsU("Prop.DistanceX", VisExistsFlags.visExistsAnywhere) = 0 Then
                iRow = shpMap.AddNamedRow(VisSectionIndices.visSectionProp, "DistanceX", 0)
                shpMap.CellsSRC(VisSectionIndices.visSectionProp, iRow, VisCellIndices.visCustPropsLabel).Formula = "=""Distance X"""
                shpMap.CellsSRC(VisSectionIndices.visSectionProp, iRow, VisCellIndices.visCustPropsType).Formula = "=2"
            Else
                iRow = shpMap.Cells("Prop.DistanceX").Row
            End If

            shpMap.CellsSRC(VisSectionIndices.visSectionProp, iRow, VisCellIndices.visCustPropsValue).Formula = "=" & distX

            If shpMap.CellExistsU("Prop.DistanceY", VisExistsFlags.visExistsAnywhere) = 0 Then
                iRow = shpMap.AddNamedRow(VisSectionIndices.visSectionProp, "DistanceY", 0)
                shpMap.CellsSRC(VisSectionIndices.visSectionProp, iRow, VisCellIndices.visCustPropsLabel).Formula = "=""Distance Y"""
                shpMap.CellsSRC(VisSectionIndices.visSectionProp, iRow, VisCellIndices.visCustPropsType).Formula = "=2"
            Else
                iRow = shpMap.Cells("Prop.DistanceY").Row
            End If

            shpMap.CellsSRC(VisSectionIndices.visSectionProp, iRow, VisCellIndices.visCustPropsValue).Formula = "=" & distY

            If shpMap.SectionExists(VisSectionIndices.visSectionHyperlink, VisExistsFlags.visExistsAnywhere) = 0 Then
                shpMap.AddSection(VisSectionIndices.visSectionHyperlink)
            End If

            If shpMap.CellExistsU("Hyperlink.Map", Microsoft.Office.Interop.Visio.VisExistsFlags.visExistsAnywhere) = 0 Then
                iRow = shpMap.AddNamedRow(VisSectionIndices.visSectionHyperlink, "Map", 0)
                shpMap.CellsSRC(VisSectionIndices.visSectionHyperlink, iRow, VisCellIndices.visHLinkDefault).Formula = "=1"
                shpMap.CellsSRC(VisSectionIndices.visSectionHyperlink, iRow, VisCellIndices.visHLinkDescription).Formula = "=""Show in Windows Live Local"""
                shpMap.CellsSRC(VisSectionIndices.visSectionHyperlink, iRow, VisCellIndices.visHLinkNewWin).Formula = "=1"
            Else
                iRow = shpMap.Cells("Hyperlink.Map").Row
            End If

            Dim hLink As String
            Dim elv As Integer
            If mappingApplication.Units = MapPoint.GeoUnits.geoMiles Then
                elv = 18 - CInt((18 * (mappingMap.Altitude / 24854)))
            Else
                elv = 18 - CInt((18 * (mappingMap.Altitude / 39999)))
            End If

            hLink = "http://local.live.com/default.aspx?cp=" & Format(oLocs(0).Latitude, "0.000000") & "%7c" & Format(oLocs(0).Longitude, "0.000000") & "&style=h&lvl=" & elv & "&v=1"

            shpMap.CellsSRC(VisSectionIndices.visSectionHyperlink, iRow, VisCellIndices.visHLinkAddress).Formula = "=""" & hLink & """"


        Catch com As COMException
            '********* visio snippet vb.net vis0056vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(com, "Com+ Policy")
            If (rethrow) Then
                Throw
            End If

        Catch ex As Exception
            ' add exception handler here
            '********* visio snippet vb.net vis0059vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If

        End Try

        Return shpMap

    End Function



#End Region

#Region " gilles kohl's calcpos - - code to compute latitude and longitude from mappoint location data "

    ' Compute latitude and longitude given a location object
    ' Author: Gilles Kohl
    ' (gilles@compuserve.com)
    ' 
    ' This code is copyrighted freeware - use freely, but please leave this
    ' header intact. Suggestions and comments welcome.

    Function Arccos(ByVal x As Double) As Double
        If x = 1 Then
            Arccos = 0
            Exit Function
        End If
        Arccos = Atan(-x / Sqrt(-x * x + 1)) + 2 * Atan(1)
    End Function

    Sub CalcPos _
        (ByVal objMap As MapPoint.Map, _
         ByVal locX As MapPoint.Location, _
         ByRef dblLat As Double, _
         ByRef dblLon As Double)

        Try


            If objMap Is Nothing Then
                Throw New System.ArgumentNullException("MapCalcPos", _
                    "objMap is Null.")
                Exit Sub
            End If

            If locX Is Nothing Then
                Throw New System.ArgumentNullException("MapCalcPos", _
                    "Location is Null.")
            End If

            Dim locNorthPole As MapPoint.Location = Nothing
            Dim locSantaCruz As MapPoint.Location = Nothing
            Static dblHalfEarth As Double ' Half circumference of the earth (as a sphere)
            Static dblQuarterEarth As Double ' Quarter circumference of the earth (as a sphere)
            Static Pi As Double

            ' Check if initialization already done
            If locNorthPole Is Nothing Then
                locNorthPole = objMap.GetLocation(90, 0)
                locSantaCruz = objMap.GetLocation(0, -90)

                ' Compute distance between north and south poles == half earth circumference
                dblHalfEarth = objMap.Distance(locNorthPole, objMap.GetLocation(-90, 0))

                ' Quarter of that is the max distance a point may be away from locSantaCruz and still be in western hemisphere
                dblQuarterEarth = dblHalfEarth / 2
                Pi = 3.14159265358979
            End If

            ' Compute latitude from distance to north pole
            dblLat = 90 - 180 * objMap.Distance(locNorthPole, locX) / dblHalfEarth

            Dim l As Double
            Dim d As Double

            ' Compute great circle distance to locX from point on Greenwich meridian and computed Latitude
            d = objMap.Distance(objMap.GetLocation(dblLat, 0), locX)

            ' convert latitude to radian
            l = (dblLat / 180) * Pi

            ' Compute Longitude from great circle distance
            dblLon = 180 * Arccos((Cos((d * 2 * Pi) / (2 * dblHalfEarth)) - Sin(l) * Sin(l)) / (Cos(l) * Cos(l))) / Pi

            ' Correct longitude sign if located in western hemisphere
            If objMap.Distance(locSantaCruz, locX) < dblQuarterEarth Then dblLon = -dblLon

        Catch com As COMException
            ' add com exception handler here
            '********* visio snippet vb.net vis0056vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(com, "Com+ Policy")
            If (rethrow) Then
                Throw
            End If
        Catch ex As Exception
            ' add exception handler here
            '********* visio snippet vb.net vis0059vb ******************
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If

        End Try
    End Sub

#End Region






End Class
